Struct AsyncReadGuard
Represents a hold on an AsyncReadWriteLock in read mode. Disposing the instance leaves the lock.
Implements
Namespace: Singulink.Threading
Assembly: Singulink.Threading.dll
Syntax
public struct AsyncReadGuard : IDisposable
Remarks
Guards returned from TryEnter methods may not have entered the lock: check IsEntered. Disposing a guard that did not enter
the lock does nothing, so a guard can always be assigned to a using declaration.
The guard can be disposed on any thread, so it can be held across an await. Disposing it never waits.
Disposing the same guard twice does nothing the second time, also when two threads dispose it at the same time.
A copy of a guard is a second handle to the same hold, and only one of the two may be disposed. Disposing both releases the hold twice. If no reader holds the lock by then, the second disposal throws a SynchronizationLockException. If other readers still hold it, the second disposal releases one of their holds instead, and a writer can then enter while the reader that lost its hold is still reading.
A copy is easily made without meaning to. A using statement over a variable that already holds the guard,
using (guard) { }, disposes a hidden copy and leaves the variable looking undisposed, so a later guard.Dispose() releases a second
time. Use using var guard = await … or using (await …) { }, which dispose the guard itself. A guard kept in a
readonly field is copied by every call to Dispose(), so each call releases again: keep a guard in a local variable
or in a field that is not read-only. The guard is marked [NonCopyable]: the Singulink.CodeAnalysis.Analyzers analyzer, which comes
with this package, reports copies of it (SCA1001).
Properties
| Name | Description |
|---|---|
| IsDefault | Gets a value indicating whether the instance is in its default, uninitialized state. |
| IsDisposed | Gets a value indicating whether the object has been disposed. |
| IsEntered | Gets a value indicating whether the guard entered the lock. Always true for guards obtained from
EnterReadGuardAsync(CancellationToken); a guard obtained from a |
Methods
| Name | Description |
|---|---|
| Dispose() | Leaves the lock. Does nothing if the guard did not enter the lock or has already been disposed. |