Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. public static class WaitHandleAsyncExtension
  2. {
  3. public static async Task<bool> WaitOneAsync(this WaitHandle handle, int millisecondsTimeout, CancellationToken cancellationToken)
  4. {
  5. RegisteredWaitHandle registeredHandle = null;
  6. var tokenRegistration = new CancellationTokenRegistration();
  7. try
  8. {
  9. var tcs = new TaskCompletionSource<bool>();
  10. registeredHandle = ThreadPool.RegisterWaitForSingleObject(
  11. handle,
  12. (state, timedOut) => ((TaskCompletionSource<bool>)state).TrySetResult(!timedOut),
  13. tcs,
  14. millisecondsTimeout,
  15. true);
  16. tokenRegistration = cancellationToken.Register(
  17. state => ((TaskCompletionSource<bool>)state).TrySetCanceled(),
  18. tcs);
  19. return await tcs.Task;
  20. }
  21. finally
  22. {
  23. registeredHandle?.Unregister(null);
  24. tokenRegistration.Dispose();
  25. }
  26. }
  27.  
  28. public static Task<bool> WaitOneAsync(this WaitHandle handle, TimeSpan timeout, CancellationToken cancellationToken)
  29. {
  30. return handle.WaitOneAsync((int)timeout.TotalMilliseconds, cancellationToken);
  31. }
  32.  
  33. public static Task<bool> WaitOneAsync(this WaitHandle handle, CancellationToken cancellationToken)
  34. {
  35. return handle.WaitOneAsync(Timeout.Infinite, cancellationToken);
  36. }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement