Last Updated on January 24, 2018 by Aram
Would you like to show your user a progress bar when your application is performing a long operation, such as loading a big number of records, or processing a huge file like an excel sheet or upgrading your desktop app?
The BackgrounderWorker leverages your application to do an asynchronous operation while you can display a nicely looking progress bar as well as reporting the progress status for your user.
The BackgroundWorker is an event-driven way to perform an operation on a separate and dedicated thread, it is mostly used when you need to show the user a friendly progress while you are operating a long running process such as downloading files, connecting to database and getting results…etc.
The idea behind the BackgroundWorker comes from its name; it processes some operations in the background and any other operation can be performed in parallel meanwhile.
Major Functions
The BackgroundWorker has 3 major events:
- DoWork
- ProgressChanged
- RunWorkerCompleted
The DoWork
event gets handled once the method RunWorkerAsync
is called. That’s it, to set up for a background operation, add an event handler for the DoWork
event. Call your time-consuming operation in this event handler, and then call RunWorkerAsync
to start the operation.
To receive notifications of progress updates, like updating a progress bar’s current value, handle the ProgressChanged
event. To receive a notification when the operation is completed, handle the RunWorkerCompleted
event.
BackgroundWorker vs Thread
The BackgroundWorker class basically abstracts the Thread creation and monitoring process. Also the BackgroundWorker helps to isolate from having to lock memory yourself, which is the case when using threads, in addition to that it reduces the possibilities of race conditions (a race condition is an undesirable situation that occurs when a device or system attempts to perform two or more operations at the same time).
Moreover, the BackgroundWorker is designed to be easily plugged in and work inside any windows form.
Both BackgroundWorker and thread share same concept yet the BackgroundWorker is designed to make threading simpler.
An example of BackgroundWorker in C# Windows Form
Below are the steps to implement the BackgroundWorker into a simple windows form in C#:
- Create a new windows forms solution
- From the Toolbox tab in left side of visual studio, drag a BackgroundWorker and drop it into the new form
- From the same toolbox, drag and drop a progress bar, a text box and 2 labels.
- The following code is the actual implementation of the BackgroundWorker in C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
public partial class BackgroundWorker : Form
{
public BackgroundWorker()
{
InitializeComponent();
bgWorker.DoWork += BgWorker_DoWork;
bgWorker.ProgressChanged += BgWorker_ProgressChanged;
bgWorker.RunWorkerCompleted += BgWorker_RunWorkerCompleted;
}
private void btnStartCounting_Click(object sender, EventArgs e)
{
progressBar.Maximum = Convert.ToInt32(txtCount.Text);
lblStatus.ForeColor = Color.Red;
lblStatus.Text = "Counting...";
bgWorker.WorkerReportsProgress = true;
bgWorker.RunWorkerAsync();
}
private void BgWorker_DoWork(object sender, DoWorkEventArgs e)
{
for (var Counter = 1; Counter <= progressBar.Maximum; Counter++)
{
bgWorker.ReportProgress(Counter);
System.Threading.Thread.Sleep(50);
}
}
private void BgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
lblStatus.ForeColor = Color.Green;
lblStatus.Text = "Done";
}
private void BgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lblPercent.Text = e.ProgressPercentage.ToString();
progressBar.Value = e.ProgressPercentage;
}
}
|
Fig1: Ready state of the application.
Fig2: Working state of the application.
Fig3: Finished State of the application.
Conclusion
BackgroundWorker provides a simple and easy way to achieve threading in Windows applications, its event-driven nature simplifies the complexity of a normal thread to 3 major functionalities that you can consume to provide the user with some status or progress indicator while doing some long running operation.
I hope that this article was helpful enough for you to understand the BackgroundWorker and how to use it. Please let me know if you have any thoughts or face any issues while trying the code in this article. Feel free to like and share this article. 🙂