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 onthread1
, and from that I’m starting another thread (thread2
). - While
thread2
is processing some files I would like to update aLabel
on theForm
with the current status ofthread2
‘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