# VBForums CodeBank > CodeBank - C# >  Using the BackgroundWorker Component

## jmcilhinney

VB version here.

Create a new Windows Forms project. Add a Label, a ProgressBar and a BackgroundWorker to the form. Set the BackgroundWorker's WorkerReportsProgress property to True. Add the following code then run the project.
CSharp Code:
private void Form1_Load(object sender, EventArgs e){    // Raise the DoWork event in a worker thread.    this.backgroundWorker1.RunWorkerAsync();} // This method is executed in a worker thread.private void backgroundWorker1_DoWork(object sender,                                      DoWorkEventArgs e){    BackgroundWorker worker = (BackgroundWorker)sender;     for (int i = 1; i <= 100; i++)    {        // Raise the ProgressChanged event in the UI thread.        worker.ReportProgress(i, i + " iterations complete");         // Perform some time-consuming operation here.        System.Threading.Thread.Sleep(250);    }} // This method is executed in the UI thread.private void backgroundWorker1_ProgressChanged(object sender,                                               ProgressChangedEventArgs e){    this.progressBar1.Value = e.ProgressPercentage;    this.label1.Text = e.UserState as string;} // This method is executed in the UI thread.private void backgroundWorker1_RunWorkerCompleted(object sender,                                                  RunWorkerCompletedEventArgs e){    this.label1.Text = "Operation complete";}
Note that if you paste that code into your own form you'll need to go to the Properties window in the designer to attach the event handlers for it to work.

----------


## jmcilhinney

E.g. Perform a loop in the worker thread with a number of iterations determined by the value set in a NumericUpDown:
CSharp Code:
private void button1_Click(object sender, EventArgs e)
{
    this.backgroundWorker1.RunWorkerAsync(Convert.ToInt32(this.numericUpDown1.Value));
}
 private void backgroundWorker1_DoWork(object sender,
                                      DoWorkEventArgs e)
{
    BackgroundWorker worker = (BackgroundWorker)sender;
    int iterationCount = 0;
     if (e.Argument is int)
    {
        iterationCount = (int)e.Argument;
    }
     for (int i = 0; i < iterationCount; i++)
    {
        // Do something here.
    }
}

----------


## jmcilhinney

Here are two examples that contrast using a BackgroundWorker to update the UI as the work is done and using it to update the UI only once the work is complete:
CSharp Code:
private void backgroundWorker1_DoWork(object sender,                                      DoWorkEventArgs e){    BackgroundWorker worker = (BackgroundWorker)sender;     foreach (string filePath in System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)))    {        worker.ReportProgress(0, System.IO.Path.GetFileName(filePath));    }} private void backgroundWorker1_ProgressChanged(object sender,                                               ProgressChangedEventArgs e){    string fileName = (string)e.UserState;     this.listBox1.Items.Add(fileName);}

CSharp Code:
private void backgroundWorker1_DoWork(object sender,                                      DoWorkEventArgs e){    BackgroundWorker worker = (BackgroundWorker)sender;    string[] fileNames = System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));     for (int index = 0; index < fileNames.GetUpperBound(0); index++)    {        fileNames[index] = System.IO.Path.GetFileName(fileNames[index]);    }     e.Result = fileNames;} private void backgroundWorker1_RunWorkerCompleted(object sender,                                                  RunWorkerCompletedEventArgs e){    string[] fileNames = (string[])e.Result;     this.listBox1.Items.AddRange(fileNames);}
These examples show how you can pass data to the UI from a BackgroundWorker in two different ways without having to explicitly delegate, which is one of the first things everyone has trouble with when multi-threading.

Note that for the first example to work the WorkerReportsProgress property must be set to True.

----------


## jmcilhinney

Here is a new example based on the code from the first post. Follow the same instructions as before but this time also set the WorkerSupportsCancellation property of the BackgroundWorker to True and add a Button to the form. Now add this code to your form:
CSharp Code:
private void Form1_Load(object sender, EventArgs e){    // Raise the DoWork event in a worker thread.    this.backgroundWorker1.RunWorkerAsync();} private void backgroundWorker1_DoWork(object sender,                                      DoWorkEventArgs e){    BackgroundWorker worker = (BackgroundWorker)sender;     for (int i = 1; i <= 100; i++)    {        if (worker.CancellationPending)        {            // The user has cancelled the background operation.            e.Cancel = true;            break;        }         // Raise the ProgressChanged event in the UI thread.        worker.ReportProgress(i, i + " iterations complete");         // Perform some time-consuming operation here.        System.Threading.Thread.Sleep(250);    }} // This method is executed in the UI thread.private void backgroundWorker1_ProgressChanged(object sender,                                               ProgressChangedEventArgs e){    this.progressBar1.Value = e.ProgressPercentage;    this.label1.Text = e.UserState as string;} // This method is executed in the UI thread.private void backgroundWorker1_RunWorkerCompleted(object sender,                                                  RunWorkerCompletedEventArgs e){    if (e.Cancelled)    {        // The background operation was cancelled.        this.label1.Text = "Operation cancelled";    }    else    {        // The background operation completed normally.        this.label1.Text = "Operation complete";    }} private void button1_Click(object sender, EventArgs e){    // Only cancel the background operation if there is a background operation in progress.    if (this.backgroundWorker1.IsBusy)    {        this.backgroundWorker1.CancelAsync();    }}
If you run the project and let it go then the ProgressBar will fill and eventually the Label will report that the operation completed. If, however, you click the Button at some point, the Progressbar will halt and the Label will report that the operation was cancelled.

----------

