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();
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.