Implementing a cancellation option
This recipe shows an example on how to cancel an asynchronous operation on a thread pool.
Getting ready
To step into this recipe, you will need Visual Studio 2015. There are no other prerequisites. The source code for this recipe can be found in BookSamples\Chapter3\Recipe4
.
How to do it...
To understand how to implement a cancellation option on a thread, 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 static System.Console; using static System.Threading.Thread;
Add the following code snippet below the
Main
method:static void AsyncOperation1(CancellationToken token) { WriteLine("Starting the first task"); for (int i = 0; i < 5; i++) { if (token.IsCancellationRequested) { WriteLine("The first task has been canceled."); return; } Sleep(TimeSpan.FromSeconds(1)); } WriteLine...