Wrapping ManualResetEvent as awaitable task
I'd like to await on a manual reset event with time-out and observing
cancellation. I've come up with something like below. Is there a way to
make this happen without taking on and blocking a thread from ThreadPool?
static Task<bool> TaskFromWaitHandle(WaitHandle mre, int timeout,
CancellationToken ct)
{
return Task.Run(() =>
{
bool s = WaitHandle.WaitAny(new WaitHandle[] { mre, ct.WaitHandle
}, timeout) == 0;
ct.ThrowIfCancellationRequested();
return s;
}, ct);
}
// ...
if (await TaskFromWaitHandle(manualResetEvent, 1000, cts.Token))
{
// true if event was set
}
else
{
// false if timed out, exception if cancelled
}
No comments:
Post a Comment