Click or drag to resize

AsyncReaderWriterLock Class

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

Namespace:  Neon.Tasks
Assembly:  Neon.Common (in Neon.Common.dll) Version: 2.1.0
public class AsyncReaderWriterLock : IDisposable

The AsyncReaderWriterLock type exposes the following members.

Public methodAsyncReaderWriterLock
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 methodGetReadLockAsync
Acquires a non-exclusive read lock.
Public methodGetType
Gets the Type of the current instance.
(Inherited from Object.)
Public methodGetWriteLockAsync
Acquires an exclusive write lock.
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.)

This class can be used to grant a single writer task exclusive access to a resource or multiple reader tasks. This class is pretty easy to use. Simply instantiate an instance and then call GetReadLockAsync or GetWriteLockAsync within a using statement:

var rwLock = new AsyncReaderWriterLock();

using (await rwLock.GetReadLockAsync())
    // Protected reading code

using (await rwLock.GetWriteLockAsync())
    // Protected writing 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 rwLock   = new AsyncReaderWriterLock();
var readLock = await rwLock.GetReadLockAsync();

// Protected reading code.


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

This class is implemented is fairly simple and always favors writers over readers. Also, all waiting readers will be released together.

Note Note
AsyncReaderWriterLock does not support any kind of reentrant Task locking support. Child tasks will be considered to be completely independent of the parent and will not inherit the parent's lock and a single task will not be able to acquire the same lock multiple times.
Thread Safety
Instance members of this type are safe for multi-threaded operations.
See Also