Implementing a cancelation option
This recipe is about implementing the cancelation process for task-based asynchronous operations. You will learn how to use the cancelation token properly for tasks and how to find out whether a task is canceled before it was actually run.
Getting ready
To start with this recipe, you will need Visual Studio 2015. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter4\Recipe6
.
How to do it...
To implement a cancelation option for task-based asynchronous operations, perform the following steps:
Start Visual Studio 2015. 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; using static System.Console; using static System.Threading.Thread;
Add the following code snippet below the
Main
method:static int TaskMethod(string name, int seconds, CancellationToken token) { WriteLine( $"Task {name} is running...