Class AsyncMutex
Implements an async
/await
friendly equivalent of Mutex.
Namespace: Neon.Tasks
Assembly: Neon.Common.dll
Syntax
public class AsyncMutex
Remarks
This class can be used to grant a task exclusive access to a resource. This class is
pretty easy to use. Simply instantiate an instance and then call AcquireAsync()
within a using
statement:
var mutex = new AsyncMutex();
using (await mutex.Acquire())
{
// Protected code
}
note
Be very sure to include the await
within the using
statement to avoid
hard to debug problems. The await
ensures that the using
statement
will dispose the acquired lock as opposed to the Task that returns
the lock.
Applications that cannot use a using
statement may release the lock explicitly
by disposing the object returned by the lock method, like this:
var mutex = new AsyncMutex();
var myLock = await mutex.AcquireAsync();
// Protected code.
myLock.Dispose();
AsyncMutex's Dispose() method ensures that any tasks waiting for a lock will be unblocked with an ObjectDisposedException.
REENTRANCY NOT SUPPORTED
IMPORTANT: This class does not allow a single task to acquire the lock more than once. This differs from how the regular Mutex classes work which do allow a single thread to acquire the mutex more than once.
This means that you cannot expect to acquire a mutex in a task and then call into a method that will also attempt to acquire the same mutex. Doing this will result in a deadlock.
var mutex = new AsyncMutex();
using (await mutex.Acquire())
{
using (await mutex.Acquire()) // $lt;--- This will block forever
{
// Protected code
}
}
You can use AsyncReentrantMutex instead.
Constructors
AsyncMutex()
Constructor.
Declaration
public AsyncMutex()
Methods
AcquireAsync()
Acquires exclusive access to the mutex.
Declaration
public NonDisposableTask<IDisposable> AcquireAsync()
Returns
Type | Description |
---|---|
NonDisposableTask<IDisposable> | The IDisposable instance to be disposed to release the lock. |
Exceptions
Type | Condition |
---|---|
ObjectDisposedException | Thrown if the mutex is disposed before or after this method is called. |
Close()
Releases any important resources associated with the instance.
Declaration
public void Close()
Remarks
note
This method will cause a ObjectDisposedException to be thrown on any task waiting to acquire this mutex.
Dispose()
Releases any important resources associated with the instance.
Declaration
public void Dispose()
Remarks
note
This method will cause a ObjectDisposedException to be thrown on any task waiting to acquire this mutex.
Dispose(bool)
Releases any important resources associated with the instance.
Declaration
protected void Dispose(bool disposing)
Parameters
Type | Name | Description |
---|---|---|
bool | disposing | Pass |
~AsyncMutex()
Finalizer.
Declaration
protected ~AsyncMutex()