执行在UI线程委托(使用消息泵)线程、消息、UI

2023-09-03 01:12:09 作者:16.我先让你一掌

我有一个处理与外部服务的通信后台线程。每次后台线程接收到一个消息,我想将它传递给供进一步处理UI线程(显示给用户)。

I have a background thread that handles communication with an external service. Each time the background thread receives a message I'd like to pass it to the UI thread for further processing (displaying to user).

目前我做了一个在Timer.Tick定期汇总,并填写了后台线程一个线程安全的消息队列。但是这种解决方案是次优。

Currently I've made a thread safe message queue that is pooled periodically in Timer.Tick and filled in the background thread. But this solution is sub optimal.

你知道如何使用消息泵从后台线程事件传递到UI线程?

Do you know how to use message pump to pass events from background thread to ui thread?

推荐答案

有一些技巧。

Control.Invoke() (等)

我发现这个WinForms的技术始终好用,但要知道,有你需要得到正确的一些微妙的规则。我试图捕捉一般情况下,工作的实现,正确处理规则在code段我已经posted其他地方的计算器。

I've found this winforms technique consistently easy to use, but be aware that there are some subtle rules you need to get right. I've tried to capture a general, working implementation that properly handles the rules in a code segment I've posted elsewhere on stackoverflow.

的SynchronizationContext

我还没有到多使用这种技术需要的,所以我真的不能说什么意义了。你应该知道它的存在,但是。我相信这是一种有效的方式,以确保东西被称为在特定线程的上下文中,即使该线程的没有的UI线程。

I haven't needed to use this technique much, so I can't really say anything meaningful about it. You should know that it exists, however. I believe that it's an effective way to ensure something gets called in a particular thread's context, even if that thread is not the ui thread.

DispatcherObject.Dispatcher

如果您正在使用WPF的WPF控件一般会从 DispatcherObject的获得供应调度对象。这比 Control.Invoke(),但也更复杂的功能更丰富的同步技术。请务必仔细阅读文档。

If you're working with WPF, the WPF controls will generally derive from DispatcherObject to supply the Dispatcher object. This is a more feature-rich synchronization technique than the Control.Invoke(), but also more complex. Be sure to read the docs carefully.