How to Implement a Background Worker Thread that Supports Cancellation (How to Stop A Background Thread)

30-05-2012

The background worker in .net provides a method CancelAsync() to cancel a background
worker.

However, calling this method will not stop a worker thread there has to be
several things you have to implement before.

1. First of all, for a BackgroundWorker to respond to a CancelAsync, you
must set the WorkerSupportsCancellation flag.

2. The CancelAsync doesn’t do anything other than setting the
CancellationPending flag. So you have to manage to check this flag and stop
working from the DoWork event you provide.

Following is a simple example:

This code starts and stops a continuous alarm.

        private static BackgroundWorker _thread = new BackgroundWorker();

        // The do work delegate
        private static void threadwork(object sender, DoWorkEventArgs e)
        {
            while (!((BackgroundWorker)sender).CancellationPending)  // <- Notice the check of the CancellationPending Flag!
            {
                BeepFor(800, 3000);
                BeepFor(1000, 1);
            }
        }

        // Starts the alarm
        public static void StartAlarm()
        {

            _thread.DoWork += threadwork;
            _thread.WorkerSupportsCancellation = true;
            _thread.RunWorkerAsync();
        }

        // Stops the alarm (simply sets the CancellationPending flag)
        public static void StopAlarm()
        {
            _thread.CancelAsync();
        }

Menol

One thought on “How to Implement a Background Worker Thread that Supports Cancellation (How to Stop A Background Thread)

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: