BackgroundWorker is designed to allow you to perform heavy or lengthy operations in a separate thread using the user interface. If you run a lengthy process in a user interface thread, your user interface will likely freeze until the process completes.
However, BackgroundWorker takes a step forward by simplifying the threading process for you. If you have to create your own thread to perform a heavy or lengthy process, you will need to use delegates to access the user interface thread to update the progress bar, for example. With BackgroundWorker, you donβt need any delegates, because the BackgroundWorker ProgressChanged event is already running in the user interface thread, and you can add your interface update code there.
To start BackgroundWorker, you need to call RunWorkerAsync () :
this.backgroundWorker.RunWorkerAsync();
To manually stop the call, execute CancelAsync () ...
this.backgroundWorker.CancelAsync();
And then check the CancellationPending property from DoWork , as shown in the following example:
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { // Example heavy operation for (int i = 0; i <= 999999; i++) { // Sleep for 10ms to simulate work System.Threading.Thread.Sleep(10); // Report the progress now this.backgroundWorker.ReportProgress(i); // Cancel process if it was flagged to be stopped. if (this.backgroundWorker.CancellationPending) { e.Cancel = true; return; } } }
I wrote an article on how to use BackgroundWorker on my blog. You can check it here: Using the BackgroundWorker component in C #
David Azzopardi
source share