Adding cancellation and progress with BackgroundWorker
The BackgroundWorker
supports two extra features: cancellation and progress. We already looked at cooperative cancellation with the CancellationTokenSource
and CancellationToken
types, but the BackgroundWorker
defines its own mechanism (it was created long before the latter types were).
In this recipe, we'll take a look at adding cancelation to the primes counting endeavor. Also, in a long running operation it's nice to indicate to the user how things are progressing. The BackgroundWorker
has good support for that, too.
Getting ready
We'll continue with the CH11.AsyncCalcWithBackgroundWorker
project. Alternatively, you can make a copy of it and work on that.
How to do it...
We'll add a Cancel button and a ProgressBar
and use the support of BackgroundWorker
for these features.
Open
MainWindow.xaml
. Add a Cancel button to the secondStackPanel
, right after the Calculate button:<Button Content="Cancel" Padding="4" x:Name="_cancelButton" ...