Click or drag to resize

AsyncMutex Class

Implements an async/await friendly equivalent of Mutex.
Inheritance Hierarchy

Namespace:  Neon.Tasks
Assembly:  Neon.Common (in Neon.Common.dll) Version: 2.14.0
public class AsyncMutex : IDisposable

The AsyncMutex type exposes the following members.

Public methodAsyncMutex
Public methodAcquireAsync
Acquires exclusive access to the mutex.
Public methodClose
Releases any important resources associated with the instance.
Public methodDispose
Releases any important resources associated with the instance.
Protected methodDispose(Boolean)
Releases any important resources associated with the instance.
Public methodEquals
Determines whether the specified object is equal to the current object.
(Inherited from Object.)
Protected methodFinalize
(Overrides ObjectFinalize.)
Public methodGetHashCode
Serves as the default hash function.
(Inherited from Object.)
Public methodGetType
Gets the Type of the current instance.
(Inherited from Object.)
Protected methodMemberwiseClone
Creates a shallow copy of the current Object.
(Inherited from Object.)
Public methodToString
Returns a string that represents the current object.
(Inherited from Object.)
Note Note

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.

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 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.


AsyncMutex's Dispose method ensures that any tasks waiting for a lock will be unblocked with an ObjectDisposedException.

Thread Safety
Instance members of this type are safe for multi-threaded operations.
See Also