tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Cancel CancellationTokenSource after a timeout

24 Jan 2013 1 mins 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 .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.