本文介绍了执行在UI线程委托(使用消息泵)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个处理与外部服务的通信后台线程。每次后台线程接收到一个消息,我想将它传递给供进一步处理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?

推荐答案

有一些技巧。

  1. 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.

这篇关于执行在UI线程委托(使用消息泵)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:15