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

This entry was posted in C#.Net and tagged , , , , . Bookmark the permalink.

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

  1. Tabitha Maynor says:

    Excellent post. I used to be checking constantly this blog and I am inspired!

Leave a Reply

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