BackgroundWorker class not only exists in C# but also in other .NET implementations like VB.NET, F# and C++. It’s a class that allows us execute a task on a separate thread. It belongs to the System.ComponentModel namespace and System.dll assembly.
Normally intensive tasks like database queries and web service calls can freeze the UI hence providing a terrible user experience. In visual studio, you can either drag the backgroundworker component from the toolbox or create it programmatically in your code.
You instantiate a backgroundworker with an empty constructor and attach an event handler in the doWork event. We then do our intensive job in this event handler. RunWorkerAsync() method executes the task.
Attach an event handler to the ProgressChnaged event to report progress back to the UI. Finally attach an event handler to the RunWorkerCompleted() event to get notified when the task is finished.
Questions this Examples helps answer.
- How do we use backgroundworker component.
- C# winforms threading example.
- How do we report progress to the UI while using backgroundworker.
- C# ProgressBar example with threads.
- How to handle cancellation in backgroundworker in c#.
Asssumptions.
We assume that you can drag a backgroundworker component in visual studio onto your winforms.
Screenshot
- Here’s the screenshot of the project.
When task is cancelled:
When task is completed:
Here's the Source Code:
Lets have a look at the source code.
Form1.cs
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace BgWorker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void startBtn_Click(object sender, EventArgs e)
{
//START BG WORKER
backgroundWorker1.RunWorkerAsync();
}
private void cancelBtn_Click(object sender, EventArgs e)
{
//REQUEST CANCELLATION
backgroundWorker1.CancelAsync();
}
//RUN BG STUFF HERE.NO GUI HERE PLEASE
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 100; i++)
{
//CHECK FOR CANCELLATION FIRST
if (backgroundWorker1.CancellationPending)
{
//CANCEL
e.Cancel = true;
}
else
{
simulateHeavyJob();
backgroundWorker1.ReportProgress(i);
}
}
}
//THIS UPDATES GUI.OUR PROGRESSBAR
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
percentageLabel.Text = e.ProgressPercentage.ToString() + " %";
}
//WHEN JOB IS DONE THIS IS CALLED.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
display("You have Cancelled");
progressBar1.Value = 0;
percentageLabel.Text = "0";
}
else
{
display("Work completed successfully");
}
}
//SIMULATE HEAVY JOB
private void simulateHeavyJob()
{
//SUSPEND THREAD FOR 100 MS
Thread.Sleep(100);
}
//DISPLAY MSG BOX
private void display(String text)
{
MessageBox.Show(text);
}
}
}
Download
Download the full project below:
How To Run
- Download the project above.
- Import into your Visual studio.
- Run the project.
More
YouTube
- Visit our channel for more examples like these.
- Lets share tips and ideas in our Facebook Page.
Oclemy,Cheers.