The BackgroundWorker
class allows you to run an operation on a separate, dedicated thread. Time-consuming operations, such as calling third party API/service, downloads and database transactions, can cause your user interface to stop responding. You should use BackgroundWorkder
when you want a responsive user interface and you must perform time-consuming operations.
using System;
using System.ComponentModel;
using System.Threading;
namespace TestConsole
{
class Program
{
public static void Main(string[] args)
{
var backgroundWorker = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
backgroundWorker.DoWork += new DoWorkEventHandler(DoLongWork);
backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(
ProgressChanged);
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
OperationCompleted);
backgroundWorker.RunWorkerAsync();
Thread.Sleep(3000);
backgroundWorker.CancelAsync();
Console.WriteLine("Main thread ends");
Console.ReadKey();
}
public static void DoLongWork(object sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
Console.WriteLine("Operation has started");
for (var i = 1; i <= 5; i++)
{
if ((worker.CancellationPending == true))
{
Console.WriteLine("Operation has been cancelled in between");
e.Cancel = true;
break;
}
Thread.Sleep(1000);
worker.ReportProgress((i * 20));
}
Console.WriteLine("End of DoLongWork method");
}
public static void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("Operation has completed {0}%", e.ProgressPercentage);
}
public static void OperationCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine(
"Operation has either completed successfully or has been cancelled");
}
}
}
I have provided rich comments in the program so that it would be easy for you to understand how BackgroundWorker
works. You can also learn more about BackgroundWorker
by commenting/uncommenting some lines and see their impact. For example: If you could comment line which sets WorkerReportProgress = true;
and see if progress is reported, i.e., updateProgress
method is called or not.