gpt4 book ai didi

c# - Dispatcher 是可以在 C# 中传递的对象吗?

转载 作者:行者123 更新时间:2023-12-03 12:55:20 26 4
gpt4 key购买 nike

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();
}
}

这可能不是使用 Dispatchers 的最佳方式,但它演示了如何将对它的引用存储为字段,就像 C# 中的其他对象一样。

关于c# - Dispatcher 是可以在 C# 中传递的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35071007/

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