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.
- DoWork - Your actual background work goes in here.
- ProgressChanged - When there is a progress in the background work.
- 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#.
- <ProgressBar x:Name="progressbar" HorizontalAlignment="Left" Height="14" Margin="191,74,0,0" VerticalAlignment="Top" Width="133"/>
- <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="249,97,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
- BackgroundWorker bg;
- public MainWindow()
- {
- InitializeComponent();
- bg = new BackgroundWorker();
- bg.DoWork += Bg_DoWork;
- bg.ProgressChanged += Bg_ProgressChanged;
- bg.RunWorkerCompleted += Bg_RunWorkerCompleted;
- bg.WorkerReportsProgress = true;
- }
- private void Bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- MessageBox.Show("Task completed");
- }
- private void Bg_ProgressChanged(object sender, ProgressChangedEventArgs e) {
- progressbar.Value += 1;
- }
- private void Bg_DoWork(object sender, DoWorkEventArgs e) {
- for (int i = 1; i & lt; = 10; i++) {
- Thread.Sleep(1000); //do some task
- bg.ReportProgress(0);
- }
- }
In order to make this stuff work, you need to trigger the DoWork event; for that, I am using button click event.
- private void button_Click(object sender, RoutedEventArgs e)
- {
- progressbar.Value = 0;
- progressbar.Maximum = 10;
- bg.RunWorkerAsync();
- }
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.
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.

Tapan PatelPosted Jul 27, 2016, 9:05 AM
Thank you for your feedback.
kalu singh raoPosted Jul 27, 2016, 1:54 AM
Good Starting