Background Worker in C#

>>> Article has moved to codingsonata.com

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#:

  1. Create a new windows forms solution
  2. From the Toolbox tab in left side of visual studio, drag a BackgroundWorker and drop it into the new form
  3. From the same toolbox, drag and drop a progress bar, a text box and 2 labels.
  4. The following code is the actual implementation of the BackgroundWorker in C#
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;
        }

    }
Demo
backgroundworker-ready-state

Fig1: Ready state of the application.

backgroundworker-running

Fig2: Working state of the application.

backgroundworker-complete

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. 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s