csharp-asynxex

AsyncEx, library for asynchronous programming in C#

  • 1 min

AsyncEx is an open-source library developed in C# by Stephen Cleary that simplifies asynchronous programming in .NET.

Asynchronous programming always has its difficulties to implement correctly. This leads to errors and unwanted behaviors, which are also very hard to detect.

This is where AsyncEx comes in. It provides a variety of types and methods that make writing asynchronous code easier, reduce complexity, and improve performance.

Among the various utilities it provides, the most popular and well-known are AsyncLock, which allows locking in an asynchronous task, and AsyncManualResetEvent, which allows event synchronization between multiple threads.

Other functionalities include asynchronous and concurrent collections, AsyncMonitor, AsyncSemaphore, AsyncCountdownEvent, AsyncReaderWriterLock, AsyncLazy, and AsyncContext.

How to Use AsyncEx

We can easily add the library to a .NET project via the corresponding NuGet package.

Install-Package Nito.AsyncEx

Here is an example of how to use AsyncLock from AsyncEx, taken from the library’s documentation.

private readonly AsyncLock _mutex = new AsyncLock();
public async Task UseLockAsync()
{
  // AsyncLock can be locked asynchronously
  using (await _mutex.LockAsync())
  {
    // It's safe to await while the lock is held
    await Task.Delay(TimeSpan.FromSeconds(1));
  }
}
Copied!