.NET 4.5 Baby Steps, Part 2: Task timeout cancellation

Other posts in this series can be found on the Series Index Page

Introduction

When Tasks were introduced in .NET 4, one of the fantastic abilities was to be able to pass in a CancellationToken and use that to cancel or break out of tasks (think like a cancel button on a file copy).

So in the following code, we create a cancellation source and pass the token to the task. It will output the date/time until you press Enter. Then we call the Cancel() method, and it stops.

var cancelTokenSource = new System.Threading.CancellationTokenSource();

Task.Factory.StartNew(() =>
{
    while (!cancelTokenSource.IsCancellationRequested)
    {
        Console.WriteLine(DateTime.Now.ToLongTimeString());
        Thread.Sleep(1000);
    }
}, cancelTokenSource.Token);

Console.WriteLine("Press any key to cancel");
Console.ReadLine();
cancelTokenSource.Cancel();
Console.WriteLine("Done");
Console.ReadLine();

What is new in .NET 4.5?

.NET 4.5 adds a fantastic new feature to this: the ability to cancel automatically after a set timeout! All we need to do is change the constructor and set the timeout. In the demo below, it is set to three seconds.

It is also important to note that it is time from when you create the token source—not when the task starts.

var cancelTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(3));

Below, in the screen capture, see how the word Done does not appear but the processing stops? That is because it is cancelled (processing stopped), but I never pressed any keys—so it is still waiting for the ReadLine() above Done.

Attachments