Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Background Worker Class in C#
The BackgroundWorker class in C# allows you to run long-running operations on a separate thread while keeping the user interface responsive. It provides a simple way to execute tasks in the background and communicate with the main thread for progress updates and completion notifications.
BackgroundWorker is particularly useful in Windows Forms applications where intensive tasks need to run without freezing the UI. It handles thread management automatically and provides events for progress reporting and task completion.
Key Properties
| Property | Description |
|---|---|
| CancellationPending | Indicates whether the application has requested cancellation of the background operation |
| IsBusy | Gets a value indicating whether the BackgroundWorker is currently running an asynchronous operation |
| WorkerReportsProgress | Gets or sets whether the BackgroundWorker can report progress updates |
| WorkerSupportsCancellation | Gets or sets whether the BackgroundWorker supports asynchronous cancellation |
Key Events
BackgroundWorker provides three main events −
DoWork − Occurs when the background operation starts
ProgressChanged − Occurs when progress is reported
RunWorkerCompleted − Occurs when the background operation is completed or cancelled
Basic Usage Example
using System;
using System.ComponentModel;
using System.Threading;
class Program {
static BackgroundWorker backgroundWorker;
static void Main(string[] args) {
backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.DoWork += BackgroundWorker_DoWork;
backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
Console.WriteLine("Starting background task...");
backgroundWorker.RunWorkerAsync();
// Keep main thread alive
Thread.Sleep(6000);
}
static void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) {
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 5; i++) {
if (worker.CancellationPending) {
e.Cancel = true;
break;
}
Thread.Sleep(1000); // Simulate work
worker.ReportProgress(i * 20, $"Processing step {i}");
}
e.Result = "Task completed successfully";
}
static void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) {
Console.WriteLine($"Progress: {e.ProgressPercentage}% - {e.UserState}");
}
static void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
if (e.Cancelled) {
Console.WriteLine("Task was cancelled");
} else if (e.Error != null) {
Console.WriteLine($"Error occurred: {e.Error.Message}");
} else {
Console.WriteLine($"Task completed: {e.Result}");
}
}
}
The output of the above code is −
Starting background task... Progress: 20% - Processing step 1 Progress: 40% - Processing step 2 Progress: 60% - Processing step 3 Progress: 80% - Processing step 4 Progress: 100% - Processing step 5 Task completed: Task completed successfully
Example with Cancellation Support
using System;
using System.ComponentModel;
using System.Threading;
class CancellationExample {
static BackgroundWorker worker;
static void Main(string[] args) {
worker = new BackgroundWorker();
worker.WorkerSupportsCancellation = true;
worker.WorkerReportsProgress = true;
worker.DoWork += Worker_DoWork;
worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
Console.WriteLine("Starting long-running task...");
worker.RunWorkerAsync();
// Cancel after 2.5 seconds
Thread.Sleep(2500);
Console.WriteLine("Requesting cancellation...");
worker.CancelAsync();
Thread.Sleep(3000); // Wait for completion
}
static void Worker_DoWork(object sender, DoWorkEventArgs e) {
BackgroundWorker bgWorker = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++) {
if (bgWorker.CancellationPending) {
e.Cancel = true;
Console.WriteLine("Cancellation detected, stopping work...");
return;
}
Console.WriteLine($"Working on task {i}...");
Thread.Sleep(500);
}
e.Result = "All tasks completed";
}
static void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
if (e.Cancelled) {
Console.WriteLine("Operation was cancelled");
} else {
Console.WriteLine($"Operation completed: {e.Result}");
}
}
}
The output of the above code is −
Starting long-running task... Working on task 1... Working on task 2... Working on task 3... Working on task 4... Working on task 5... Requesting cancellation... Cancellation detected, stopping work... Operation was cancelled
Conclusion
BackgroundWorker provides a simple and effective way to perform long-running operations without blocking the UI thread. It handles thread synchronization automatically and offers built-in support for progress reporting and cancellation, making it ideal for desktop applications that need responsive user interfaces.
