Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theodorzoulias/cc7f38d5423eee9f238f349605fc400a to your computer and use it in GitHub Desktop.
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
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