Class AsyncLock
A mutual-exclusion lock for asynchronous use.
public sealed class AsyncLock : IDisposable
- Inheritance
-
AsyncLock
- Implements
- Inherited Members
Remarks
Note that this lock operates without regard for the current thread, unlike the C# lock
mechanism, which allows recursive locks as long as it occurs on the same thread.
AsyncLock only allows one lock at a time, even from the same thread; an attempt to recursively obtain another lock will cause a deadlock.
Constructors
AsyncLock()
Initializes a new instance of the AsyncLock class.
public AsyncLock()
Methods
Dispose()
Closes and releases all resources used by the object.
public void Dispose()
Lock(CancellationToken)
Synchronously acquires the lock.
public IDisposable Lock(CancellationToken cancellationToken = default)
Parameters
cancellationToken
CancellationTokenThe cancellation token used to cancel.
Returns
- IDisposable
A disposable that releases the lock when disposed.
Exceptions
- OperationCanceledException
cancellationToken
was canceled.- ObjectDisposedException
The current instance has already been disposed.
LockAsync(CancellationToken)
Asynchronously acquires the lock.
public Task<IDisposable> LockAsync(CancellationToken cancellationToken = default)
Parameters
cancellationToken
CancellationTokenThe cancellation token used to cancel.
Returns
- Task<IDisposable>
A task that represents the asynchronous operation. The value of its Result property contains a disposable that releases the lock when disposed.
Exceptions
- ObjectDisposedException
The current instance has already been disposed.
TryLock(int, out IDisposable)
Synchronously tries to acquire the lock.
public bool TryLock(int millisecondsTimeout, out IDisposable lockDisposable)
Parameters
millisecondsTimeout
intThe number of milliseconds to wait, Infinite (-1) to wait indefinitely, or zero to return immediately whether the lock is acquired or not.
lockDisposable
IDisposableIf the lock is acquired, will be set to a disposable that releases the lock when disposed. If the lock is not acquired, will be null.
Returns
- bool
true if the lock was acquired, or false if the lock was not acquired before the timeout expired.
Exceptions
- ObjectDisposedException
The current instance has already been disposed.