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 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.