Implementing a cancellation option
This recipe is about implementing the cancellation process for task-based asynchronous operations. We will learn how to use the cancellation token properly for tasks, and how to find out whether a task is cancelled before it was actually run.
Getting ready
To start with this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter4\Recipe6
.
How to do it...
For implementing a cancellation option for task-based asynchronous operations, perform the following steps:
Start Visual Studio 2012. Create a new C# Console Application project.
In the
Program.cs
file, add the followingusing
directives:using System; using System.Threading; using System.Threading.Tasks;
Add the following code snippet below the
Main
method:private static int TaskMethod(string name, int seconds,CancellationToken token){ Console.WriteLine("Task {0} is running on a thread id{1}. Is thread pool thread: {2}...