9 Canceling background tasks

 

This chapter covers

  • Canceling operations
  • The CancellationToken and Cancellation-TokenSource classes
  • Implementing timeouts
  • Combining cancellation sources

In the previous chapter, we talked about how to run stuff in the background. In this chapter, we are going to talk about how to make it stop. The .NET library provides a standard mechanism for signaling that a background operation should end, which is called CancellationToken. The CancellationToken class is used consistently for (almost) all cancelable operations in the .NET library itself and in most third-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 Running a background thread forever
var thread = new Thread(BackgroundProc);
thread.Start();
Console.ReadKey();
 
void BackgroundProc()
{
   int i=0;
   while(true)
   {
      Console.WriteLine(i++);
   }
}

9.2 Canceling using an exception

9.3 Getting a callback when the caller cancels our operation

9.4 Implementing timeouts

9.5 Combining cancellation methods

9.6 Special cancellation tokens

Summary