Not really; you pretty much need to check the IsCancelled
property of the BGW periodically to properly cancel. If it's important that a given operation explicitly not know about the BGW then there are a few options.
One thing you can do if it's really important to not expose the BGW is to use a CancellationToken
instead. You can create a CancellationTokenSource
and expose it to whatever is responsible for canceling the task, and then pass the Token
value of the cts to whatever is responsible for being canceled.
Another option is that you could pass a Func<bool>
as a parameter to DoJob
. That function, when invoked, would return whether or not the task has currently requested cancellation. You would then call it like so:
workClassInstance.DoJob(()=> worker.CancellationPending);
You've now "hidden" the background worker from the workClassInstance
and only exposed that aspect of its functionality that it needs, namely whether or not cancellation has been requested.