简体   繁体   English

是否可以为非 UI 工作线程创建 Dispatcher (System.Windows.Threading)?

[英]Is it possible to create Dispatcher (System.Windows.Threading) for a non-UI worker thread?

Actually I want to have one dedicated worker thread for handling events from both main and other worker threads.实际上,我想要一个专用的工作线程来处理来自主线程和其他工作线程的事件。 This thread must also be able to invoke delegates in other threads.该线程还必须能够调用其他线程中的委托。 (The thread receives commands from the main thread, executes some of them in other worker threads, processes the completion and progress events from these commands, and inform the main thread about how he is doing). (线程从主线程接收命令,在其他工作线程中执行其中一些命令,处理来自这些命令的完成和进度事件,并通知主线程他正在做什么)。

All this could be done manually by implementing an analogue of the message queue from delegates in the desired thread.所有这些都可以通过在所需线程中实现来自委托的消息队列的模拟来手动完成。 However, I would prefer a higher level approach if such exists.但是,如果存在这种方法,我更喜欢更高级别的方法。 From the documentation I got the impression that the Dispatcher class is well suited for this purpose.从文档中我得到的印象是 Dispatcher 类非常适合此目的。 I also got feeling that an object of this class can be created in any thread, but didn't find any example.我也觉得这个类的对象可以在任何线程中创建,但没有找到任何例子。 Is my feeling wrong?是我的感觉不对吗?

There is nothing built-in, but it is quite easy to create a custom TaskScheduler that schedules work on a specific thread.没有内置任何东西,但是创建一个自定义TaskScheduler来安排特定线程上的工作非常容易。 Most implementations use the handy BlockingCollection class as a queue.大多数实现使用方便的BlockingCollection类作为队列。 Here is one implementation, and here is another one. 是一种实现, 是另一种实现。 You could customize any of these implementations to your needs, and then use it like this:您可以根据需要自定义这些实现中的任何一个,然后像这样使用它:

var myScheduler = new SingleThreadTaskScheduler();
var task = Task.Factory.StartNew(() => DoSomething(), default,
    TaskCreationOptions.None, myScheduler);

There is also the option to use the fancy TaskFactory class, so that you can start tasks on this scheduler with less code:还可以选择使用精美的TaskFactory类,以便您可以使用更少的代码在此调度程序上启动任务:

var myFactory = new TaskFactory(new SingleThreadTaskScheduler());
var task = myFactory.StartNew(() => DoSomething());

Personally I am not a fan of this class, because it makes me confused with the similarity between TaskFactory and the Task.Factory property.我个人不是这个类的粉丝,因为它让我对TaskFactoryTask.Factory属性之间的相似TaskFactoryTask.Factory

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM