How to stop BackgroundWorker whose `DoWork` handler only contains one (long-running) statement?

71 views Asked by At

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?

1

There are 1 answers

0
stakx - no longer contributing On

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:

void CallTimeConsumerFunction(Func<bool> shouldCancel)
{                          // ^^^^^^^^^^^^^^^^^^^^^^^
                           // add this; can be called to find out whether to abort or not
    … // possibly lengthy operation
    if (shouldCancel()) return;
    … // possibly lengthy operation
}

private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    CallTimeConsumerFunction(shouldCancel: () => backgroundWorker.CancellationPending);
}                         // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^