How do I update the GUI from another thread?

How do I update the GUI from another thread?

This blog post is all about How do I update the GUI from another thread? for example we want to update some process status in the label from the background thread.

Requirement

  • I have a Form running on thread1, and from that I’m starting another thread (thread2).
  • While thread2 is processing some files I would like to update a Label on the Form with the current status of thread2‘s work.

Solution

The solution is simple. Implement the below logic.

// Running on the background / worker thread

form.Label.Invoke((MethodInvoker)delegate {
    // Running on the UI thread
    form.Label.Text = "Process Text Here";
});
// Back on the background / worker thread

You can also use Action delegate:

// Running on the background / worker thread

form.Label.Invoke(new Action(() => 
 // Running on the UI thread
    form.Label.Text = "Process Text Here";
));
// Back on the background / worker thread