Question

I've got a GUI form which is acting as the main thread, while I've got a different class for the actual work which is needed to be done.

Is there a way to properly check the CancellationPending property of the worker since it's being activated from a different class, other than passing the worker as a parameter for the "DoJob" method so it could check the property?

The code (in the main class):

// This method is registered as the DoWork method for the worker
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    workClassInstance.DoJob();
}

private void buttonCancel_Click(object sender, RoutedEventArgs e)
{
    if (bw.WorkerSupportsCancellation == true)
    {
        bw.CancelAsync();
    }
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top