Background Worker Delegate & invokers

I have a background worker that does a lot of GUI interactions, but my problem is that all these objects are in the main thread (as I know), and I need to call all this time, something that my code does longer and less readable.
1) Do you know how I can create a generic method that will reference these GUI elements.
2) Is there an easier way to counter this?

Thanks in advance.

+4
source share
1 answer

With BackgroundWorker you can ReportProgress and pass the percentage completed and the object. You can create a class containing data to pass to the user interface, and then pass it as an object.

ProgressChanged An event can manage user interface objects because it will run in a user interface thread.

Example for your problem

private void Form1_Load(object sender, EventArgs e) { backgroundWorker1.RunWorkerAsync(); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { List<string> items = new List<string>(); items.Add("Starting"); System.Threading.Thread.Sleep(2500); backgroundWorker1.ReportProgress(25, items.ToArray()); items.Add("Halfway there"); System.Threading.Thread.Sleep(2500); backgroundWorker1.ReportProgress(50, items.ToArray()); items.Add("Almost there"); System.Threading.Thread.Sleep(2500); backgroundWorker1.ReportProgress(75, items.ToArray()); items.Add("Done"); System.Threading.Thread.Sleep(2500); backgroundWorker1.ReportProgress(100, items.ToArray()); } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { listBox1.Items.Clear(); listBox1.Items.AddRange((string [])e.UserState); this.Text = e.ProgressPercentage.ToString(); } 

The second argument to ReportProgress is the type of the object. you can put whatever you want and apply it to the corresponding type on the other hand.

+3
source

All Articles