James Jeffery
James Jeffery

Reputation: 12599

Canceling Threads

I have an application that uses 20 threads. It's an email client that uses threads to mail from.

Currently the threads are created in the main thread. But I am wondering, what if I want to cancel the whole operation? The only way I can see of doing it is killing the main thread ... thus ending the program.

Would I have to create a thread that encapsulates the threads for mailing so I can kill the encapsulating thread?

I am currently using BackgroundWorker by the way and it's a WF application.

Upvotes: 3

Views: 192

Answers (1)

Aaronaught
Aaronaught

Reputation: 122674

If you are using a BackgroundWorker then you already have all of the infrastructure you need to cancel the operation. Simply set WorkerSupportsCancellation to true on the BackgroundWorker, and invoke the worker's CancelAsync method when you want to cancel.

Obviously you have to write the worker code to honour the cancellation. You do this by checking the CancellationPending property of the BackgroundWorker.

MSDN has an example of using this property.


Note - I am a bit confused by the combination of BackgroundWorker and 20 threads; a BackgroundWorker only uses one thread by itself. Are you spinning off 20 BackgroundWorkers? If so, how do you ensure that they're properly disposed? If you need that much concurrency in a Winforms app then it's better to use asynchronous delegates or the Thread Pool.

If you are creating actual threads, one common way of implementing a cancellation flag is to use a ManualResetEvent. If you wait on this event with zero timeout, it acts as a thread-safe status flag. An example usage would be:

ManualResetEvent cancelEvent = new ManualResetEvent(false);
for (int i = 0; i < 20; i++)
{
    ThreadPool.QueueUserWorkItem(s =>
    {
        // Do some work
        if (cancelEvent.WaitOne(0, true))
            return;
        // Do some more work
        // etc.
    });
}

Then at some point later if you write cancelEvent.Set(), every worker will stop its work as soon as it hits the status check.

Upvotes: 3

Related Questions