Sunday, February 17, 2008

BackgroundWorker Class .Net

Ever heard of A BackGroundWorker Component in .Net.?

Even though these features are now available in .Net many still opt the Thread for any background works.

Today we shall discuss about the BackgroundWorker Component in .Net.

Its mainly used when we have to perform some actions without hindering the program flow.Say like downloading something in the background or so.

I shall explain the process with the help of an example.

From the toolbox include a background worker to the project.

The major works done by backgroundworker are in the events,
  1. DoWork
  2. RunWorkerCompleted
  3. ProgressChanged
We'll discuss about all of these today.

The DoWork is the event in which the background work executes.The RunworkerCompleted shows us the results after completion of the background event and the progresschanged is used to show the completion percentage of work.

Moving on to the example.

I am using a button to invoke the backgroundworker class.The example is just calculating some value.In the compute function that I use, you can include any code that you require in the actual scenario.

private void _computeButton_Click(object sender, EventArgs e)
{
_computeText.Clear();
_computeButton.Enabled = false;
_backgroundWorker.RunWorkerAsync();
}

private int Compute()
{
int index = 10;
int total = 0;
for (int i = 0; i < index; i++)
{
total += i;
///used the raise the Progress Changed Event
_backgroundWorker.ReportProgress(i * 10 + 10);
Thread.Sleep(1000);
}
return total;
}

private void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
e.Result = Compute();
}

private void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Display(e.Result.ToString());
}

private void _backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
///A progress Bar showing the percentage of work completed
_backgroundWorkerProgress.Value = e.ProgressPercentage;
}

//to access a control created in another thread, an explicit invoke of the control is required private delegate void DisplayDelegate(string text);
private void Display(string text)
{
if (InvokeRequired)
{
Invoke(new DisplayDelegate(Display), new object[] { text });
}
else
{ _computeText.Text = text;
_computeButton.Enabled = true;
}
}

On clicking the ComputeButton now the backgroundworker starts its execution,eventually showing the progress in the progressbar and on completion shows the result in the textbox.

Hope this helps..