Skip to content

Instantly share code, notes, and snippets.

@SchreinerK
Created July 10, 2019 05:37
Show Gist options
  • Save SchreinerK/816baf9e817139186af1cc50d689b610 to your computer and use it in GitHub Desktop.
Save SchreinerK/816baf9e817139186af1cc50d689b610 to your computer and use it in GitHub Desktop.
WaitHandle.WaitOneAsync(...)
public static class WaitHandleAsyncExtension
{
public static async Task<bool> WaitOneAsync(this WaitHandle handle, int millisecondsTimeout, CancellationToken cancellationToken)
{
RegisteredWaitHandle registeredHandle = null;
var tokenRegistration = new CancellationTokenRegistration();
try
{
var tcs = new TaskCompletionSource<bool>();
registeredHandle = ThreadPool.RegisterWaitForSingleObject(
handle,
(state, timedOut) => ((TaskCompletionSource<bool>)state).TrySetResult(!timedOut),
tcs,
millisecondsTimeout,
true);
tokenRegistration = cancellationToken.Register(
state => ((TaskCompletionSource<bool>)state).TrySetCanceled(),
tcs);
return await tcs.Task;
}
finally
{
registeredHandle?.Unregister(null);
tokenRegistration.Dispose();
}
}
public static Task<bool> WaitOneAsync(this WaitHandle handle, TimeSpan timeout, CancellationToken cancellationToken)
{
return handle.WaitOneAsync((int)timeout.TotalMilliseconds, cancellationToken);
}
public static Task<bool> WaitOneAsync(this WaitHandle handle, CancellationToken cancellationToken)
{
return handle.WaitOneAsync(Timeout.Infinite, cancellationToken);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment