9 Canceling background tasks
This chapter covers
- Canceling operations
- The CancellationToken and CancellationTokenSource classes
- Implementing timeouts
- Combining cancellations sources
In the previous chapter, we talked about how to run stuff in the background. In this chapter, we are going to talk about making it stop. The .net library provides a standard mechanism for signaling that a background operation should end, called CancellationToken. The CancellationToken class is used consistently for (almost) all cancelable operations in the .net library itself and in most 3rd party libraries.
9.1 Introducing CancellationToken
For this chapter, we need an example of a long-running operation we can cancel. So, let’s write a short program that will count for the longest time possible - forever.
Listing 9.1 Run background thread forever
var thread = new Thread(BackgroundProc); thread.Start(); Console.ReadKey(); void BackgroundProc() { int i=0; while(true) { Console.WriteLine(i++); } }