gpt4 book ai didi

c# - 使用 Application.Current.Dispatcher 进行单元测试

转载 作者:行者123 更新时间:2023-12-05 03:10:51 25 4
gpt4 key购买 nike

我读过很多关于 Application.Current.Dispacher 在单元测试时为 null 的帖子。这正是我遇到的问题。我找到了 This这正是我要找的。但是,似乎当我去实现这个时我无法编译。错误为:

Cannot access private constructor 'Dispatcher' here.

在上面的帖子中,他们说有很多方法可以实现我下面的代码。因为他没有检查多线程安全检查。我如何进行这些检查并使其编译?

    public static Dispatcher RootDispatcher
{
get
{
if (_rootDispatcher == null)
{

if (Application.Current != null)
{
_rootDispatcher = Application.Current.Dispatcher;
}
else
{
var thread = Thread.CurrentThread;
_rootDispatcher = new Dispatcher(thread);
}
}
return _rootDispatcher;
}
internal set { _rootDispatcher = value; }
}

最佳答案

编译错误是由于您尝试使用的构造函数实际上是私有(private)的(并且您使用它不接受的参数调用它)

查看 Dispatcher.Current 的文档,它说:

Gets the for the thread currently executing and creates a new if one is not already associated with the thread.

因此,您可以使用:

  • _rootDispatcher = Dispatcher.CurrentDispatcher;

产生一个 Dispatcher 实例。

作为一种优化,您可以始终将 Dispatcher.CurrentDispatcher 用作“RootDispatcher”。无论 Application.Current 是否存在。

如果您在生产和测试中都遇到此代码,则需要区分这些场景。在生产中使用应用程序的调度程序,并在单元测试中使用“任何”调度程序 (Dispatcher.Current),因为应用程序不存在。

关于c# - 使用 Application.Current.Dispatcher 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38524815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com