Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added synchronous TryLock/TryEnter methods with Disposable out param. #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/Nito.AsyncEx.Coordination/AsyncLock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,29 @@ public IDisposable Lock()
{
return Lock(CancellationToken.None);
}

/// <summary>
/// Attempts to acquire the lock. Returns true if the current thread acquires the lock; otherwise, false.
/// </summary>
/// <param name="disposable">The IDisposable if lock is successfully acquired, otherwise null.</param>
/// <returns>True if the current thread acquires the lock; otherwise, false.</returns>
public bool TryLock(out IDisposable disposable)
{
lock (_mutex)
{
if (!_taken)
{
// If the lock is available, take it immediately.
_taken = true;

disposable = _cachedKeyTask.Result;
return true;
}

disposable = null;
return false;
}
}

/// <summary>
/// Releases the lock.
Expand Down
8 changes: 8 additions & 0 deletions src/Nito.AsyncEx.Coordination/AsyncMonitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,14 @@ public IDisposable Enter()
return Enter(CancellationToken.None);
}

/// <summary>
/// Attempts to synchronously enter the monitor. Returns true if the current thread acquires the lock; otherwise, false.
/// </summary>
public bool TryEnter(out IDisposable disposable)
{
return _asyncLock.TryLock(out disposable);
}

/// <summary>
/// Asynchronously waits for a pulse signal on this monitor. The monitor MUST already be entered when calling this method, and it will still be entered when this method returns, even if the method is cancelled. This method internally will leave the monitor while waiting for a notification.
/// </summary>
Expand Down