Wednesday, December 19, 2012

Cross thread control update

Here is a very nice way to update a UI control from a worker thread...


string newText = "abc"; // running on worker thread
this.Invoke((MethodInvoker)delegate {
    someLabel.Text = newText; // runs on UI thread
});
Here is how it is done in WPF
if (someLabel.Dispatcher.CheckAccess())
    someLabel.Text = newText;
else
    someLabel.Dispatcher.Invoke(new Action(() => someLabel.Text = newText), null);
    DoEvents();
And a WPF 'DoEvents' equivalent
public void DoEvents()
{
   try
   {
      Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(delegate { }));
   }
   catch { }
}

No comments:

Post a Comment