Skip to content

Instantly share code, notes, and snippets.

@5cover
Created June 6, 2023 21:02
Show Gist options
  • Save 5cover/e06607e8ef5141cafa743d6e5d464bb7 to your computer and use it in GitHub Desktop.
Save 5cover/e06607e8ef5141cafa743d6e5d464bb7 to your computer and use it in GitHub Desktop.
C# Task WithTimeout() extension method
public static async Task WithTimeout(this Task task, TimeSpan timeout)
{
CancellationTokenSource cts = new();
if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token)))
{
cts.Cancel();
}
else
{
throw new TimeoutException();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment