Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BackgroundWorker multithread access to form

I am using 5 BackgroundWorker objects running at the same time for a certain purpose, and all of them have to change the same label. How do I do that?

How do I modify the form from more than one thread then? And how do i do it in case i want to change a public string?

like image 276
Marcelo Avatar asked Feb 02 '10 10:02

Marcelo


1 Answers

Use Control.Invoke with a delegate.

In your background worker thread, instead of saying

label4.Text = "Hello";

say

label4.Invoke(new Action(() =>
{
  label4.Text = "Hello";
}
));

Everything inside the { } executes on the control's thread, so you avoid the exception.

This allows you to do arbitrary changes to your user interface from a BackgroundWorker rather than just reporting progress.

like image 154
RobC Avatar answered Sep 28 '22 06:09

RobC