Closed mmaderic closed 4 years ago
You can archive that behaviour by calling LockAsync()
resp. Lock()
with an already cancelled CancellationToken
. That call would fail, if the lock has allready been taken. You could wrap that logic into a small extension method:
private static readonly CancellationTokenSource _cancelledTokenSource = new CancellationTokenSource(0);
public static bool TryLock(this AsyncLock @lock, out IDisposable token)
{
try
{
token = @lock.Lock(_cancelledTokenSource .Token);
return true;
}
catch(OperationCancelledException)
{
token = default;
return false;
}
}
This would have the advantage of beeing thread safe, as a _taken
property might be outdated, when read.
@Pretasoc is correct. _taken
is specifically not exposed because its existence would almost always encourage incorrect code.
Could you please expose _taken so we can perform checks if the lock is already taken. One such use case example would be if we would like to return from the method first if the lock is already taken.