Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create a task to wait for WaitHandle.
internal static class WaitHandleExtensions
{
public static Task AsTask(this WaitHandle handle)
{
return AsTask(handle, Timeout.InfiniteTimeSpan);
}
public static Task AsTask(this WaitHandle handle, TimeSpan timeout)
{
var tcs = new TaskCompletionSource<object>();
var registration = ThreadPool.RegisterWaitForSingleObject(
handle,
(state, timedOut) =>
{
var localTcs = (TaskCompletionSource<object>)state;
if (timedOut)
{
localTcs.TrySetCanceled();
}
else
{
localTcs.TrySetResult(null);
}
},
tcs,
timeout,
true);
tcs.Task.ContinueWith(
(_, state) => ((RegisteredWaitHandle)state).Unregister(null),
registration,
TaskScheduler.Default);
return tcs.Task;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.