Last active
May 3, 2022 09:14
-
-
Save theodorzoulias/cc7f38d5423eee9f238f349605fc400a to your computer and use it in GitHub Desktop.
Nito.AsyncEx.AsyncAutoResetEvent.WaitAsync with timeout -- https://stackoverflow.com/questions/32654509/awaitable-autoresetevent
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 async Task<bool> WaitAsync(this AsyncAutoResetEvent source, | |
TimeSpan timeout, CancellationToken cancellationToken = default) | |
{ | |
if (timeout < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(timeout)); | |
if (timeout == Timeout.InfiniteTimeSpan) | |
{ | |
await source.WaitAsync(cancellationToken); return true; | |
} | |
cancellationToken.ThrowIfCancellationRequested(); | |
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); | |
linkedCts.CancelAfter(timeout); | |
try | |
{ | |
await source.WaitAsync(linkedCts.Token); return true; | |
} | |
catch (OperationCanceledException) | |
{ | |
cancellationToken.ThrowIfCancellationRequested(); | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment