Introduction
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
component.
Background
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 DoWork
.
Using the Code
Setting up the Form.
Here I have:
- 2
TextBox
es
- 1
Label
- 1
Butt
on
- 1 Progress Bar
- 1
backgroundWorker
(under Component Section on ToolBox)
The backgroundworker
property 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));
backgroundWorker1.RunWorkerAsync(myStruct);
btnCalculate.Enabled = false;
}
When button calculate is pressed, it will call the backgroundworker.RunWorkerAsync(object)
. RunWorkerAsync
will trigger the event _DoWork
.
In the 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++)
{
backgroundWorker1.ReportProgress(i);
Thread.Sleep(100);
}
e.Result = my.X + my.Y;
}
e.Argument
is important because that is how we will unbox the object passed into the backgroundworker
component.
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 backgrroundWorker1_RunWorkerCompleted
.
As the backgroundworker
report progress it will update the _ProgressChanged
.
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 _RunWorkerCompleted
.
private void backgroundWorker1_RunWorkerCompleted
(object sender, RunWorkerCompletedEventArgs e)
{
lblAnswer.Text = e.Result.ToString();
btnCalculate.Enabled = true;
}
History
- 11th February, 2010: Initial post