Another common scenario for cancelling asynchronous tasks is to set a timeout period by using the CancellationTokenSource.CancelAfter
method. This method schedules the cancellation of any associated tasks that aren't complete within the period of time that's designated by the CancelAfter
expression.
In this recipe, we are going to create a WPF application that gets the contents of a classic book over the web and performs a word count. This time though, we are going to set a timeout period after which the task gets cancelled.
Now, let's see how we can create an asynchronous task that cancels after a specified timeout period.
Start a new project using the WPF Application project template and assign
CancelAfterTimeout
as Solution name.Begin by opening
MainWindow.xaml
and add the following XAML to create our user interface:<Window x:Class="CancelAfterTimeout.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation...