WPF Dispatcher.Invoke Style UI Element Update for WinForm Applications in C#





5.00/5 (4 votes)
Simple code wrap for updating UI elements in cross thread applications
Introduction
Developers familiar with WPF use Dispatcher.Invoke
to create a delegate for updating UI elements. The style is:
this.Dispatcher.Invoke(
DispatcherPriority.Normal,
(System.Windows.Forms.MethodInvoker)delegate()
{
// Your code here
});
However Dispatcher
is not available in Windows Forms. So generally Windows Form developers rely mainly upon updating the UI elements in ProgressChanged
event handler of background worker. However, a simple and similar way of UI update would be nice as you may want several UI updates per progress change.
The solution might be known to many or should I say most of the prolific CodeProject developers. However I still find this question being asked in numerous forums and therefore have decided to post it here. If you already know this, great, if you do not, use it.
Using the Code
As the solution is simple, I would simply put the code. I guess nothing much is there to explain.
this.Invoke((MethodInvoker)delegate {
// your UI update code here. e.g. this.Close();Label1.Text="something";
});
One important thing that you must remember while working with updating UI elements is that it is always preferred to update the elements from UI thread. ProgressChanged
is still the best place to update your UI . However it is a good practice to use this model even within ProgressChanged
to ensure trouble free element update.
Points of Interest
Doing things in simpler ways is also an efficient way. Developers working extensively on cross threading models like Port programming, Web cam and Image operations, remote methods might find this technique useful. I posted as usual for beginners to save them from "Thread Horror". Your discussions, suggestions and criticism are welcome as always.