Cancel CancellationTokenSource after a timeout
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
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.
Jiří Činčura is an independent developer, .NET, C# and Firebird expert, focusing on data and business layers, language constructs, parallelism, databases and performance. He's Microsoft Most Valuable Professional and frequent speaker. You can read his articles, guides and tips and tricks at www.tabsoverspaces.com.