Dispatcher 是一个可以在 C# 中传递的对象吗?我有一个线程调用另一个线程。当我尝试执行 Dispatcher.CheckAccess() 时,第二个线程给了我这个错误:
An object reference is requied for the non-static field, method or property 'System.Windows.Threading.Dispatcher.CheckAccess()'.
因此,我尝试在原始类中创建一个调度程序对象并将其传递给第二个类,但程序不喜欢这样并崩溃了。
代码的一般结构:
public public partial class MainView : UserControl{
public myButtonClick(Event eventObj, Session session)
{
//does some stuff and invokes Dispatcher.CheckAccess()
secondClass.startProcess(passThruString);
}
}
public class SecondClass
{
public startProcess(string passThru){
//does some other stuff and calls Dispatcher.CheckAccess() which throws error
}
}
我已通过将 Dispatcher.CheckAccess() 替换为 Dispatcher.Currentdispatcher.CheckAccess() 来纠正错误,但为什么我不能只创建调度程序对象?
最佳答案
调度程序可以像 C# 中的任何其他对象一样传递。但是,无法构造调度程序,因为构造函数已设为私有(private):
var dispatcher = new Dispatcher(); //compile error
要传递调度程序,您需要获取其他一些现有的调度程序。一种选择(正如您在更新的问题中指出的那样)是使用 Dispatcher.CurrentDispatcher
:
var dispatcher = Dispatcher.CurrentDispatcher;
SomeFunction(dispatcher);
这将创建对 Dispatcher.CurrentDispatcher
的引用,可以存储和传递该引用。
在我自己的一个项目中,我使用调度程序来避免诸如“调用线程无法访问此对象,因为不同的线程拥有它”之类的错误。这是因为在我拥有的这个特定类中,后台线程可能会尝试对 UI 线程上创建的对象执行操作。我猜你也有类似的问题。
这是我如何使用它的一个最小示例:
public class SomeClass
{
private readonly Dispatcher _dispatcher;
public SomeClass()
{
_dispatcher = Dispatcher.CurrentDispatcher;
}
public void SomeOperation()
{
InvokeIfNeeded(() => Console.WriteLine("Something"));
}
private void InvokeIfNeeded(Action action)
{
if (_dispatcher.Thread != Thread.CurrentThread)
_dispatcher.Invoke(action);
else
action();
}
}
这可能不是使用调度程序的最佳方式,但它演示了如何将对其的引用存储为字段,就像 C# 中的其他对象一样。
关于c# - Dispatcher 是一个可以在 C# 中传递的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35071007/