Created
July 10, 2019 05:37
-
-
Save SchreinerK/816baf9e817139186af1cc50d689b610 to your computer and use it in GitHub Desktop.
WaitHandle.WaitOneAsync(...)
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 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