Overview
- Is a helper class in System.ComponentModel namespace
- Manages a worker thread
- Handles automatic marshaling/invoking: can update Windows forms
Use BackgroundWorder
- Add a BackgroundWorker component to the form.
- Run it:
backgroundWorker1.RunWorkerAsync(); // Parameter can be pass to worker as well backgroundWorker1.RunWorkerAsync(Object param);
- Implement actual work in the DoWork event:
private void backgroundWorker1_DoWork( object sender, DoWorkEventArgs e){ // long task... }
- Cleanup when done:
private void backgroundWorker1_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e){ // Clean up... }
To be able to cancle background work
- Enable worker cancellation support:
backgroundWorker1 .WorkerSupportsCancellation = true;
- Cancel worker:
backgroundWorker1.CancelAsync();
- Check cancel event in DoWork event
private void backgroundWorker1_DoWork( object sender, DoWorkEventArgs e){ // long task... BackgroundWorker worker= (BackgroundWorker)sender; If (worker.CancellationPending == true) { e.Cancel = True // Cancel long task } }
- Check cancel event in RunWorkerCompleted event
private void backgroundWorker1_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e){ // Clean up... if (e.Cancelled){ MessageBox.Show("Cancelled"); } }
If need to report progress
- Enable backgrounWorker progress report:
backgroundWorker1.WorkerReportsProgress = true;
- Add a ProgressBar component to the form
- Update progress bar in ProgressChanged event:
private void backgroundWorker1_ProgressChanged( object sender, ProgressChangedEventArgs e){ BackgroundWorker worker = (BackgroundWorker)sender; worker.ReportProgress(10); }
Reference: