This lightweight library adds await support for ordinary WaitHandle objects such as ManualResetEvent, AutoResetEvent, and others.
$ dotnet add package AwaitExtensionsWaitHandle Support for .NETThis lightweight library adds await support for ordinary WaitHandle objects such as ManualResetEvent, AutoResetEvent, and others.
It exposes two simple extension methods:
GetAwaiter() — Enables await handle;ToTask() — Converts a WaitHandle into a Task that completes when the handle is signaledThis makes it easy to integrate traditional wait-based APIs into modern async/await workflows.
WaitHandle directlyasync/await patternsAdd the NuGet package to your project:
dotnet add package AwaitExtensions
Or install via the NuGet Package Manager UI.
WaitHandlevar evt = new ManualResetEvent(false);
// Somewhere in your async method:
await evt; // resumes when the event is signaled
Taskvar evt = new ManualResetEvent(false);
Task t = evt.ToTask();
await t;
public async Task WaitForSignalAsync()
{
using var evt = new ManualResetEvent(false);
_ = Task.Run(() =>
{
Thread.Sleep(1000);
evt.Set();
});
Console.WriteLine("Waiting...");
await evt;
Console.WriteLine("Signal received!");
}
The implementation internally uses:
ThreadPool.RegisterWaitForSingleObject to react to the signalTaskCompletionSource<object> to complete the returned taskThe result is a task that completes as soon as the handle is signaled.
The core implementation is based on a gist originally published by Andrew Arnott:
👉 https://gist.github.com/AArnott/1084951
Huge thanks to Andrew for sharing the elegant original version!
This package only wraps and redistributes the same idea for easier consumption.