C# Using the BackgroundWorker

Leave a comment

The background worker in the .NET Framework is used to run background operations in a background thread. This is useful if you don’t want to tie up your user interface while an operation completes, such as downloading a large file. The background worker exposes events ProgressChanged and RunWorkerCompleted, which are useful to display progress to the user in a UI scenario.

In this example, we will create a WPF form that will display a counter on a label when a user presses a Start button. The user will then be able to still use the form while the background process runs.

First, create a new project in Visual Studio of type Windowws Forms App:

This will open:

We will add:

  • A label that displays a counter
  • A button Start to start the count
  • A button that displays Hello World

We will also drag a BackgroundWorker onto the form:

Now, go to the code. Ensure below is added:

using System.ComponentModel;

Now, add code on the form load to set initial properties of the backkgroundworker:

 InitializeComponent();
 backgroundWorker1.WorkerReportsProgress = true;
 backgroundWorker1.WorkerSupportsCancellation = true;

Now, the button change code. Here we will set the event handlers for DoWork (which fires when the background process runs), ProcessChangedHandler (which fires on the background process ReportProgress), and RunWorkerCompleted (which runs on the completion of the background process):

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy != true)
            {
                backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
                backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
                backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
                backgroundWorker1.RunWorkerAsync();
            }
        }

Now, implement the code for DoWork. This will loop through a counter and sleep so we can see the counter increment. On each increment we will ReportProgress to the background process:

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            for (int i = 1; i <= 100; i++)
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress(i * 1);
                }
            }
        }

Next, we will implement ProcessChanged, which updates the label to the percentage of the progress:

 private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
 lblCounter.Text = (e.ProgressPercentage.ToString());
 }

Finally, we will set the label to “Complete”:

 private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
 lblCounter.Text = "Complete";
 }

For our Hello World button, we will display a message to the user.

 private void btnHelloWorld_Click(object sender, EventArgs e)
 {
 MessageBox.Show("Hello World");
 }

Now we can run this. When we run this, the timer increases. We can then click on the Hello World button:

The label will continue to update in the background, i.e. the UI is not tied to the background process:

Complete code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Carl.WinBackgroundCounter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy != true)
            {
                backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
                backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
                backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
                backgroundWorker1.RunWorkerAsync();
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            lblCounter.Text = "Complete";
        }
        private void btnHelloWorld_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Hello World");
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            for (int i = 1; i <= 100; i++)
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress(i * 1);
                }
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            lblCounter.Text = (e.ProgressPercentage.ToString());
        }
    }
}
<span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

See more articles on: C#

Leave a Reply

Your email address will not be published. Required fields are marked *