StephenCleary / AsyncEx

A helper library for async/await.
MIT License
3.51k stars 358 forks source link

Expose AsyncLock _taken as public get property #222

Closed mmaderic closed 4 years ago

mmaderic commented 4 years ago

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.

Pretasoc commented 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.

StephenCleary commented 4 years ago

@Pretasoc is correct. _taken is specifically not exposed because its existence would almost always encourage incorrect code.