Skip to content

Instantly share code, notes, and snippets.

@usausa
Created October 12, 2020 23:49
Show Gist options
  • Save usausa/a365ecde51af5d242525b3ed658c5afd to your computer and use it in GitHub Desktop.
Save usausa/a365ecde51af5d242525b3ed658c5afd to your computer and use it in GitHub Desktop.
Timeout for CancellationToken unsupported methods
public static class TaskExtensions
{
public static async Task<T> WithTimeout<T>(this Task<T> task, int timeout)
{
using var cts = new CancellationTokenSource();
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, cts.Token)).ConfigureAwait(false);
cts.Cancel();
return completedTask == task ? task.Result : default;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment