Adding cancelation support
Long running operations are typically performed on a different thread, which keeps the UI responsive, but that may not be enough. Applications may want to provide a way to cancel a long-running operation. Prior to .NET 4, developers used various ways to orchestrate cancelations. Starting from .NET 4 there is a standard way to convey cancelation requests.
In this recipe, we'll see how to use this cancelation mechanism.
Getting ready
Open the CH11.AsyncCalc
project. We'll enhance it with cancelation support.
How to do it...
We'll add the option to cancel the prime calculation operation.
Open
MainWindow.xaml
. Add another button to the secondStackPanel
with the following markup:<Button Content="Cancel" Padding="4" Margin="10,0,0,0" IsEnabled="False" x:Name="_cancelButton" />
Name the Calculate button
_calcButton
.Open
MainWindow.xaml.cs
. Change theCountPrimes
method to accept aCancellationToken
:static int CountPrimes(int from, int to, CancellationToken...