Simple Background Worker Using C#

Below is a simple example of a Background Worker in a timer application. Source code is at the bottom of the page.

Background Worker: a class that executes an operation on a separate thread. Allows the application to run a new thread in the background different from the mainform thread. This allows the application to run without freezing or locking up the form.

First things first: create a new project in Visual Studio (or whatever your favorite IDE is). For this example, I created a Winform application using .NET Framework 4.5.

Next, go to your form and add a Background Worker tool from the Toolbox Window. Don’t forget, if you are wanting your Background Worker to report progress back to the main thread or support cancellation, change the options below in the Properties Window for the worker:

 

Next, I added a few more components to my form where the user can input the amount of seconds they want the timer to run, a StartButton to start the timer, and a StopButton to stop the timer if the user wishes to:

 

After this, I added a few Event Methods to the Form1.cs code behind. I will summarize and comment on the methods below and include the source code:

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace BackgroundWorkerDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            // constructor to initialize Form1 components
            InitializeComponent();
        }

        private void StartButton_Click(object sender, EventArgs e)
        {
            // Disable start button and enable stop button 
            // so user can toggle between starting and stopping the timer
            StartButton.Enabled = false;
            StopButton.Enabled = true;

            // this is one of the main parts of the background worker. 
            // Calling RunWorkerAsync() is what starts the worker in a seperate thread.
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // this is the method that runs after calling RunWorkerAsync()
            // from here, you can report back to the Main thread elasped time, progress changes, ect.
            int stoptime = Int32.Parse(TimerStop.Text.ToString());
            for (int elapsed = 0; elapsed <= stoptime; elapsed++)
            {
                // reports back progress to main thread
                backgroundWorker1.ReportProgress(elapsed);
                Thread.Sleep(1000);
                // if CancelAsync() is called, stop the backgroundWorker1 thread
                if (backgroundWorker1.CancellationPending)
                {
                    e.Cancel = true;
                    backgroundWorker1.CancelAsync();
                    TimerLeft.Text = "Canceled";
                    return;
                    
                }
            }

        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // for ProgressChanged to work, property must be enabled
            var elapsedtime = e.ProgressPercentage.ToString();
            var stoptime = Int32.Parse(TimerStop.Text.ToString());

            // compare elaspedtime to stoptime to check if timer is done
            if (Int32.Parse(elapsedtime) >= stoptime)
            {
                TimerLeft.Text = "Done!";
                backgroundWorker1.CancelAsync();
            }
            else
            {
                TimerLeft.Text = elapsedtime;
            }
            
        }

        private void StopButton_Click(object sender, EventArgs e)
        {
            // if user clicks stop button and the background worker is running, cancel the background thread
            if (backgroundWorker1.IsBusy) backgroundWorker1.CancelAsync();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // worker complete, stop the thread and toggle stop and start button enables
            backgroundWorker1.CancelAsync();
            StopButton.Enabled = false;
            StartButton.Enabled = true;

        }
    }
}




Please leave any comments below if there’s any problems or questions!