Using the BackgroundWorker component


Introduction:

The BackgroundWorker allows you to execute operations that take a long period of time such as database transaction or file downloads, asynchronously on a separate thread and allow the user interface to remain responsive.

Start an Operation in the Background:

First, you need to add an instance of the BackgroundWorker component to you application, if you use visual studio, just drag it from the toolbox to your application or you can create it manually as follow:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

To start the operation in the background you have to call the RunWorkerAsync() method of the BackgroundWorker, when you call this method the BackgroundWroker starts the execution of the background operation by raising the DoWork event, the code in the DoWork event handler is executed on a separate thread.

Example:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

//start the operation on another thread

private void btnStart_Click(object sender, EventArgs e)

{

    backgroundWorker1.RunWokerAsync();

}

//DoWork event handler is executed on a separate thread

private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)

{

    //a long running operation

    Thread.Sleep(5000);
}

You can send a parameter to the background operation using the RunWorkerAsync() method. You can recieve this parameter by using the Argument property of the instance of DoWorkEventArgs in the DoWork event handler then you cast it to use it in the background operation.

Example:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

//start the operation on another thread

private void btnStart_Click(object sender, EventArgs e)

{

    backgroundWorker1.RunWokerAsync(2000);

}

//DoWork event handler is executed on a separate thread

private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)

{

    int input = (int)e.Argument;

    //a long running operation

    Thread.Sleep(input);

}

Reporting progress of a background operation using BackgroundWorker:

By using the BackgroundWorker you have the ability to report progress updates of the executing operation. To use this options you must set the WorkerReportsProgress to true.

To start report progress you call ReportProgress() method and use it to pass a parameter that have the value of the percentage of the progress that have been completed. This method raises the BackgroundWorker.ProgressChanged event. In the event handler of the ProgressChanged you can recieve the value of the progress precentage on the main thread using the ProgressPercentage property of the instance of ProgressChangedEventArgs.

Example:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

backgroundWorker1.WorkerReportsProgress = true;

//start the operation on another thread

private void btnStart_Click(object sender, EventArgs e)

{

    backgroundWorker1.RunWokerAsync();

}

//DoWork event handler is executed on a separate thread

private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)

{

    //a long running operation

    for (int i = 1; i < 11; i++)

    {   

        Thread.Sleep(2000);

        backgroundWorker1.ReportProgress(i*10);

    }

}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)

{

    progressBar1.value = e.ProgressPercentage;

}

Cancelling a background operation using BackgroundWorker:

With the BackgroundWorker you have the ability to cancel the background operation, to do this you first must set WorkerSupportsCancellation property to true.

The next step is to call the CancelAsync() method by doing so you sets the CancellationPending property to true, by polling the CancellationPending property you can determine whether or not to cancel the background operation.

Example:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

backgroundWorker1.WorkerSupportsCancellation = true;

//start the operation on another thread

private void btnStart_Click(object sender, EventArgs e)

{

    backgroundWorker1.RunWokerAsync();

}

//a buttun to cancel the operation

private void btnCancel_Click(object sender, EventArgs e)

{

    backgroundWorker1.CancelAsync();

}

//DoWork event handler is executed on a separate thread

private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)

{

    //a long running operation

    for (int i = 1; i < 11; i++)

    {

        Thread.Sleep(2000);

        backgroundWorker1.ReportProgress(i*10);

 

        if(backgroundWorker1.CancellationPending)

        {

            e.cancel = true;

            return;

        }

    }

}

Alert the user in the completion of the background operation:

When the background operation completes, whether because the backgroud operation is completed or cancelled, the RunWorkerCompleted event is raised. You can alert the user to the completion by handling the RunWorkerCompleted event.

You can determine if the user cancelled the operation by using the Cancelled property of the instance RunWorkerCompletedEventArgs.

Example:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

//start the operation on another thread

private void btnStart_Click(object sender, EventArgs e)

{

    backgroundWorker1.RunWokerAsync();

}

//a buttun to cancel the operation

private void btnCancel_Click(object sender, EventArgs e)

{

    backgroundWorker1.CancelAsync();

} 

//DoWork event handler is executed on a separate thread

private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)

{

    //a long running operation

    for (int i = 1; i < 11; i++)

    {

        Thread.Sleep(2000);

        backgroundWorker1.ReportProgress(i*10);

 

        if (backgroundWorker1.CancellationPending)

        {

            e.Cancel = true;

            return;

        }

    }

} 

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

{

    if(e.Cancelled)

    {

        MessageBox.Show("Operation Cancelled");

    }

    else

    {

        MessageBox.Show("OperationCompleted");

    }

}


 

Return a value from the background operation:

You can return a value from the background operation that in the DoWork event handler using the Result property of the DoWorkEventArgs instance, and you can recieve it in the RunWorkerCompleted event handler using the Result property of the RunWorkerCompletedEventArgs instance.

Example:

BackgroundWorker backgroundWorker1 = new BackgroundWorker();

//start the operation on another thread

private void btnStart_Click(object sender, EventArgs e)

{

    backgroundWorker1.RunWokerAsync();

}

//DoWork event handler is executed on a separate thread

private void backgroundWorker1_DoWork(object sender, DoWorkeventArgs e)

{

    //a long running operation here

    Thread.Sleep(2000);

    //return the value here

    e.Result = 10;

}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

{

    //recieve the return value here

    int returnValue = (int)e.Result;

}

 

you can see the full code of these examples after downloading the files with this article.

Up Next
    Ebook Download
    View all
    Learn
    View all