How to Use BackgroundWorker

GM Fuster
2 min readMar 19, 2024

Just an example on how to use a BackgroundWorker for threading. Note that I am not adding null checks in here, but in real life, you should.

You can drag and drop the background worker from the toolbox, or in a console application, you can add it by using

using System.Threading;
using System.ComponentModel;

then

public BackgroundWorker worker = new BackgroundWorker();

In the constructor or wherever you decide to do it, you can do this (from System.ComponentModel:

 worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

Somewhere in your code (button probably), you need the code that should start the calculations that need to be done in the background. You do it this way:

public void StartWorker()
{
if (!Worker.IsBusy)
{
Worker.RunWorkerAsync(); //this will call the DoWork
}
}

Since we said we are allowing cancellation, in a cancel button or wherever you want to cancel from (when we said WorkerSypportsCancellation = true).

public void CancelWorker()
{
if (Worker.IsBusy)
{
Worker.CancelAsync();
}
}

You will have the code that needs to run in the background here:

private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;

//your code here

//when you need to report back so something can be shown in the screen

worker.ReportProgress(1, "some string you want to send back, could be any object");

//in your code, you should check for this regularly to check if the user cancelled
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
}

How to handle the progress being sent:

private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
e.UserState.ToString();//UserSate has the object you passed in. //In real life you sould check for null
}

To do something once the DoWork has completed:

private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
//what do you want to do if you got here because they cancelled
}
else
{
//what do you want to do if you got here because DoWork finished
}
}

And that is it.

--

--