When I cancel my async method with the following content by calling the Cancel()
method of my CancellationTokenSource
, it will stop eventually. How
I like to use an infinite delay, the code is quite clean.
If waiting
is complete WhenAny
returns and the cancellationToken
will throw. Else, the result of task
will be returned.
public static async Task WithCancellation(this Task task, CancellationToken cancellationToken)
{
using (var delayCTS = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
var waiting = Task.Delay(-1, delayCTS.Token);
var doing = task;
await Task.WhenAny(waiting, doing);
delayCTS.Cancel();
cancellationToken.ThrowIfCancellationRequested();
return await doing;
}
}