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).
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.
Do you know how to use message pump to pass events from background thread to ui thread?
You can use Control.Invoke and use a delegate. The delegate will be executed on the thread that created the control.
http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx
There are a few techniques.
Control.Invoke()
(et al)
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With