How do I update the GUI from another thread?

CruelIO picture CruelIO · Mar 19, 2009 · Viewed 693.3k times · Source

Which is the simplest way to update a Label from another Thread?

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

How could I do that?

Answer

Marc Gravell picture Marc Gravell · Mar 19, 2009

The simplest way is an anonymous method passed into Label.Invoke:

// Running on the worker thread
string newText = "abc";
form.Label.Invoke((MethodInvoker)delegate {
    // Running on the UI thread
    form.Label.Text = newText;
});
// Back on the worker thread

Notice that Invoke blocks execution until it completes--this is synchronous code. The question doesn't ask about asynchronous code, but there is lots of content on Stack Overflow about writing asynchronous code when you want to learn about it.