Created
June 6, 2023 21:02
-
-
Save 5cover/e06607e8ef5141cafa743d6e5d464bb7 to your computer and use it in GitHub Desktop.
C# Task WithTimeout() extension method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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