Skip to main content

Use C#/VB await keyword with AutoResetEvent, ManualResetEvent, or Semaphore in .NET apps.

Total Downloads
1.5K
1,492
Published
Nov 30, 2023
2y ago

Get Started

dotnet add package AsyncWaitHandle2 --version 2.0.1
ProductVersions
.NET Standard
netstandard2.0

README

Use C#/VB await keyword with AutoResetEvent, ManualResetEvent, or Semaphore in .NET apps

Extension methods for the WaitHandle class in the System.Threading namespace for your convenience. Available as NuGet package 'AsyncWaitHandle2' on nuget.org: https://www.nuget.org/packages/AsyncWaitHandle2/

Example 1 (simple await):

var e = new AutoResetEvent();
...
await e;

Example 2 (configured await):

var e = new AutoResetEvent();
var cts = new CancellationTokenSource();
...
var timeout = TimeSpan.FromSeconds(30);
try
{
  await e.ConfigureAwait(timeout, cts.Token);
}
catch (TimeOutException)
{
  ...
}
catch (OperationCanceledException)
{
  ...
}

Example 3 (WaitOneAsync):

var e = new AutoResetEvent();
var cts = new CancellationTokenSource();
...
var timeout = TimeSpan.FromSeconds(30);
bool fSignaled;
try
{
  fSignaled = await e.WaitOneAsync(timeout, cts.Token);
}
catch (OperationCanceledException)
{
  ...
}

Example 4 (WaitAnyAsync):

var events = new WaitHandle[] { new AutoResetEvent(), new ManualResetEvent() };
var cts = new CancellationTokenSource();
...
var timeout = TimeSpan.FromSeconds(30);
int signaledIndex;
try
{
  signaledIndex = await events.WaitAnyAsync(timeout, cts.Token);
}
catch (OperationCanceledException)
{
  ...
}
switch (signaledIndex)
{
  case 0: ...
  case 1: ...
  case WaitHandle.Wait...
}

Example 5 (WaitAllAsync):

var events = new WaitHandle[] { new AutoResetEvent(), new ManualResetEvent() };
var cts = new CancellationTokenSource();
...
var timeout = TimeSpan.FromSeconds(30);
bool allSignaled;
try
{
  allSignaled = await events.WaitAllAsync(timeout, cts.Token);
}
catch (OperationCanceledException)
{
  ...
}

Downloads by Version

Similar & Alternative Packages

Hand-picked matching NuGet libraries based on tags & ecosystem

Depended On By

Find packages that declare this package as a dependency. NuGet does not provide a reverse-dependency endpoint, so candidates are checked on demand.

Adoption Assessment

Assess this package against its supported frameworks, license, maintenance signals and dependency graph before making it a project standard.

Compatibility metadata lists 1 target framework; confirm the exact target used by your application.

Related Guides & Workflows

Learn how to evaluate, integrate, or audit this package in your .NET project.