Click here to Skip to main content
15,906,574 members
Articles / Desktop Programming / WPF
Tip/Trick

How To Use BackgroundWorker in C#

Rate me:
Please Sign up or sign in to vote.
4.87/5 (10 votes)
24 Jul 2016CPOL1 min read 39K   16   10
Basic implementation of background worker implementation

Introduction

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

Using the Code

Backgroundworker has three event handlers which basically takes 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 background worker has completed the work.

I have created a sample WPF application which demonstrates how to use the background worker in C#.

XML
<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"/>

On Window initialization, I am creating a new object of BackgroundWorker and registering the event handlers for the same.

C#
BackgroundWorker bg;
public MainWindow()
{
InitializeComponent();
bg = new BackgroundWorker();
bg.DoWork += Bg_DoWork;
bg.ProgressChanged += Bg_ProgressChanged;
bg.RunWorkerCompleted += Bg_RunWorkerCompleted;
bg.WorkerReportsProgress = true;
}

Here is the implementation of all three event handlers.

C#
private void Bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Task completed");
}

private void Bg_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressbar.Value += 1;
//label.Content = e.ProgressPercentage;
}

private void Bg_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 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 and for that, I am using button click event.

C#
private void button_Click(object sender, RoutedEventArgs e)
   {
           progressbar.Value = 0;
           progressbar.Maximum = 10;
           bg.RunWorkerAsync();
   }

It is a very basic example of background worker, but it is good to start with.

One must be wondering how it is updating the progress bar if it is working in the background.

Well, the ProgressChanged event handler runs on UI thread whereas DoWork runs on application thread pool. That's why despite running in the background on different thread, it is not freezing the UI and updating the progressbar upon making progress.

Please leave your comments for any question or concerns.

Points of Interest

It is really helpful to understand how background worker is useful - especially when one needs to do some task like parallel processing or sending bulk emails or transaction and keeping the UI available to user and notifying the progress.

History

  • 24th July, 2016: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
Software Developer

Comments and Discussions

 
Questionhow can we progress file saving operation Pin
farshad valizade 202317-Feb-23 18:40
farshad valizade 202317-Feb-23 18:40 
QuestionKindly explain Pin
Member 127702452-Nov-16 2:41
Member 127702452-Nov-16 2:41 
AnswerRe: Kindly explain Pin
tpatel114-Jul-17 8:02
tpatel114-Jul-17 8:02 
Thank you for pointing it out. I have corrected the typo (it must have been from HTML code).
QuestionWhy use .NET BackgroundWorker? Pin
PureNsanity26-Jul-16 6:19
professionalPureNsanity26-Jul-16 6:19 
AnswerRe: Why use .NET BackgroundWorker? Pin
tpatel127-Jul-16 10:48
tpatel127-Jul-16 10:48 
GeneralRe: Why use .NET BackgroundWorker? Pin
PureNsanity27-Jul-16 11:00
professionalPureNsanity27-Jul-16 11:00 
GeneralRe: Why use .NET BackgroundWorker? Pin
tpatel125-Aug-16 8:42
tpatel125-Aug-16 8:42 
GeneralRe: Why use .NET BackgroundWorker? Pin
PureNsanity25-Aug-16 9:14
professionalPureNsanity25-Aug-16 9:14 
GeneralRe: Why use .NET BackgroundWorker? Pin
Charles Banks13-Feb-21 13:50
professionalCharles Banks13-Feb-21 13:50 
GeneralRe: Why use .NET BackgroundWorker? Pin
PureNsanity24-Feb-21 9:49
professionalPureNsanity24-Feb-21 9:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.