Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a delegate in the ui thread (using message pump)

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?

like image 722
Piotr Czapla Avatar asked Jul 15 '09 16:07

Piotr Czapla


2 Answers

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

like image 100
Kevin Doyon Avatar answered Nov 14 '22 06:11

Kevin Doyon


There are a few techniques.

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

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

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

like image 44
Greg D Avatar answered Nov 14 '22 05:11

Greg D