Created
October 12, 2020 23:49
-
-
Save usausa/a365ecde51af5d242525b3ed658c5afd to your computer and use it in GitHub Desktop.
Timeout for CancellationToken unsupported methods
This file contains hidden or 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 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