How To Use BackgroundWorker In C#

BackgroundWorker is a class in System.ComponentModel which is used when some task needs to run in the back-end, or in a different thread, while keeping the UI available to the users (not freezing the user) and at the same time, reporting the progress of the same.

BackgroundWorker has three event handlers which basically take care of everything one needs to make it work.

  1. DoWork - Your actual background work goes in here.
  2. ProgressChanged - When there is a progress in the background work.
  3. RunWorkerCompleted - Gets called when BackgroundWorker has completed the task.

I have created a sample WPF application to demonstrate how to use the BackgroundWorker in C#.

  1. <ProgressBar x:Name="progressbar" HorizontalAlignment="Left" Height="14" Margin="191,74,0,0" VerticalAlignment="Top" Width="133"/>    
  2. <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="249,97,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>    
On Windows initialization, I am creating a new object of BackgroundWorker and registering the event handlers for the same.
  1. BackgroundWorker bg;  
  2. public MainWindow()   
  3. {  
  4.     InitializeComponent();  
  5.     bg = new BackgroundWorker();  
  6.     bg.DoWork += Bg_DoWork;  
  7.     bg.ProgressChanged += Bg_ProgressChanged;  
  8.     bg.RunWorkerCompleted += Bg_RunWorkerCompleted;  
  9.     bg.WorkerReportsProgress = true;  
  10. }  
Here is the implementation of all three event handlers.
  1. private void Bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)   
  2. {  
  3.     MessageBox.Show("Task completed");  
  4. }  
  5. private void Bg_ProgressChanged(object sender, ProgressChangedEventArgs e) {  
  6.     progressbar.Value += 1;  
  7. }  
  8. private void Bg_DoWork(object sender, DoWorkEventArgs e) {  
  9.     for (int i = 1; i & lt; = 10; i++) {  
  10.         Thread.Sleep(1000); //do some task    
  11.         bg.ReportProgress(0);  
  12.     }  
  13. }   
In order to make this stuff work, you need to trigger the DoWork event; for that, I am using button click event.
  1. private void button_Click(object sender, RoutedEventArgs e)   
  2. {  
  3.     progressbar.Value = 0;  
  4.     progressbar.Maximum = 10;  
  5.     bg.RunWorkerAsync();  
  6. }  
It is a very basic example of BackgroundWorker, but it is good to start with. 
 
One must be wondering how it updates the progress bar if it is working in the background.

Well, the ProgressChanged event handler runs on a UI thread whereas DoWork runs on application thread pool. That's why despite running in the background on different threads, it is not freezing the UI and updating the progress bar upon making progress.
 
Please leave your comments for any questions/concerns.