Update WinForm interface from a different thread

Well, this is a typical issue when you have a thread that works (i.e. a Workflow) and a UI that needs to be updated.

Let assume that you have a WinFom and you need to update its windows Title from another thread. The other thread needs to call "UpdateTitle" public method of current Form instance. If you write the following code:

 public class MainForm : Form
{
   ...
   
   void UpdateTitle(string newTitle)
   {
      this.Text = newTitle;         
   }

   ...
}

UpdateTitle will work only if you call the method from the UI thread.

In order to make this call thread safe, I found two ways, choose the one that fits your needs:-)

 

Method ONE: Using a delegate

 

 public class MainForm : Form
{
   ...
   
   private delegate void UpdateTitleDelegate(string s);
   void UpdateTitle(string newTitle)
   {
   if (this.InvokeRequired)             
      this.Invoke(new UpdateTitleDelegate                 
         (this.UpdateTitle), newTitle);         
   else         
      {             
      this.Text = newTitle;         
      }
   }

   ...
}
  

Method TWO: using MethodInvoker

  
 public class MainForm : Form
{
   ...
      
   void UpdateTitle(string newTitle)
   {
   if (this.InvokeRequired)             
      this.Invoke(new MethodInvoker(delegate()
      {
      this.Text = newTitle;    
      }));
   else         
      {             
      this.Text = newTitle;         
      }
   }
   ...
}

For more information have a look to Control.InvokeRequired property on MSDN.