.NET Zone is brought to you in partnership with:

Robert is a South African technology specialist with focus on Microsoft technologies. He is very passionate about teaching and sharing and is a Microsoft MVP & Ranger. Robert is a DZone MVB and is not an employee of DZone and has posted 75 posts at DZone. You can read more from them at their website. View Full User Profile

.NET 4.5 Baby Steps, Part 2: Task Timeout Cancellation

05.09.2012
| 3093 views |
  • submit to reddit

Introduction

When Tasks where introduced in .NET 4 one of the fantastic abilities was to be able to pass in a CancellationToken and use that to cancel/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 and 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();

CropperCapture[1]

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! So all we need to is change the constructor and set the time out. 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 and not time from 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 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.

CropperCapture[2]

AttachmentSize
Cancellation Token Demo Code7.75 KB
Published at DZone with permission of Robert Maclean, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)