I have a problem with a BackgroundWorker
whose DoWork
handler contains only one statement. Which means that I cannot check the CancellationPending
flag:
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
CallTimeConsumerFunction();
}
How can I stop this BackgroundWorker
? Is there any work-around?
Looking at .NET 4's Task Parallel Library (TPL), which came after
BackgroundWorker
and is rather well-designed, can give you an idea how you should approach this.Cancellation in the TPL is built on the idea of cooperative cancellation. This means that tasks are not forcibly stopped from the outside; instead they participate in the cancellation process by periodically checking whether cancellation has been requested and, if so, by gracefully aborting "from the inside".
I recommend you follow the TPL's example and implement cooperative cancellation. Like this comment states, inject cancellation logic into
CallTimeConsumerFunction
. For example: