开发者

How to dispatch function to gui thread?

I write custom worker component and want it 开发者_如何转开发to fire it's events on GUI thread. But I don't want it to know about any existing windows. Also sometimes I have moments when there's no window at all (transition between login and main window). So I can't use Window.Dispatcher.BeginInvoke(). What are the other ways?


Pass (or get using Current) a SynchronizationContext to your worker. This is a lower level threading object that represent a particular context of execution (usually a thread), onto which you can post custom actions using the Post method. In case of a WPF application, SynchronizationContext.Post will use Dispatcher.BeginInvoke. It's a good way to write background components that invoke events or send messages to a specific context without being tied to a particular implementation.

Plus, it's very easy to write a synchronous SynchronizationContext that doesn't use threads at all to easily unit test your component without adding any asynchronous complexity.


Great article on MSDN Magazine's WPF Threads section: Build More Responsive Apps With The Dispatcher

Contents: - Threading in WPF - Using the Dispatcher - Non-UI thread handling - Using timers

(Sorry can't format list perfectly from my phone's browser)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜