tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Cancel CancellationTokenSource after a timeout

24 Jan 2013 Multithreading/Parallelism/Asynchronous/Concurrency

Maybe you already discovered it. But in .NET 4.5 the CancellationTokenSource class has a new method CancelAfter. It allows you to signal cancellation after a specified interval aka timeout.

In .NET 4 you’d have to Wait on a Task to complete or not and if not, do the cancellation. This might go little bit off control if you have a bunch of tasks. In .NET 4.5 a handy Task.Delay was added and with await/async it was easier. But still.

Setting a timeout and basically forgetting about it is a nice little help, that will make the code little more clean and easier to comprehend.

Profile Picture Jiří Činčura is an independent developer focusing on data and business layers, language constructs, parallelism and databases. Specifically Entity Framework, asynchronous and parallel programming, cloud and Azure. He's Microsoft Most Valuable Professional and you can read his articles, guides, tips and tricks at www.tabsoverspaces.com.