Reputation: 8156
I have a background worker that does many GUI interactions, but my problem is that all of those objects are in the main thread (as I know), and I need to invoke all of the all the time, something that is making my code longer and less readable.
1) Do you know how can I create a generic method that will invoke those GUI elements.
2) Is there a more simple way to confront this?
Thanks in advance.
Upvotes: 4
Views: 5330
Reputation: 2144
With the BackgroundWorker you can ReportProgress and pass a percentage complete and an object. You could create a class to contain the data to pass to UI and then pass it as the object.
The ProgressChanged Event can manipulate UI Objects since it would be running in the UI Thread.
Example for your issue
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 in ReportProgress is an Object type. you can put whatever you want in it and cast it to the proper type on the other side.
Upvotes: 3