Sometimes you just want a simple background thread that does the work and when it is completed, it will do something with the result. Microsoft has a backgroundworker component that works like a thread on a Windows Form. I wanted to demonstrate how to use the
BackgroundWorker has three events:
DoWork - This will be the method that will handle the work when
backgroundworker is invoked to run.
ProgressChanged - This is for reporting to a progress bar.
RunWorkerCompleted - Put code here for the return results of
Using the Code
Setting up the Form.
Here I have:
- 1 Progress Bar
backgroundWorker (under Component Section on ToolBox)
WorkerReportProgress needs to be
true to report progress:
How does the
backgroundworker component run?
private void btnCalculate_Click(object sender, EventArgs e)
MyStruct myStruct = new MyStruct(int.Parse(txtX.Text),int.Parse(txtY.Text));
btnCalculate.Enabled = false;
When button calculate is pressed, it will call the
RunWorkerAsync will trigger the event
backgroundWorker1_DoWork event is where you will put your code to do something.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
MyStruct my = (MyStruct)e.Argument;
for (int i = 0; i <= 10; i++)
e.Result = my.X + my.Y;
e.Argument is important because that is how we will unbox the object passed into the
In this example will be just sleep and report progress. After a certain time it will calculate the result and return it back to the
backgroundworker report progress it will update the
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
progressBar1.Value = e.ProgressPercentage;
Finally when it is completed, it will return the result and we want to display the result so we put the code into the
private void backgroundWorker1_RunWorkerCompleted
(object sender, RunWorkerCompletedEventArgs e)
lblAnswer.Text = e.Result.ToString();
btnCalculate.Enabled = true;
- 11th February, 2010: Initial post