public async Task <int> NextAsync() { int intReturn; await _objLock.WaitAsync(); try { intReturn = _objRandom.Next(); } finally { _objLock.Release(); } return(intReturn); }
private async Task <IAsyncDisposable> TakeWriteLockCoreAsync(DebuggableSemaphoreSlim objCurrentSemaphore, SafeWriterSemaphoreRelease objRelease, CancellationToken token) { try { await objCurrentSemaphore.WaitAsync(token); if (Interlocked.Increment(ref _intCountActiveReaders) == 1) { try { // Wait for the reader lock only if there have been no other write locks before us if (_objTopLevelWriterSemaphore.CurrentCount != 0 || objCurrentSemaphore == _objTopLevelWriterSemaphore) { await _objReaderSemaphore.WaitAsync(token); } } catch { Interlocked.Decrement(ref _intCountActiveReaders); throw; } } } catch (OperationCanceledException) { //swallow this because it must be handled as a disposal in the original ExecutionContext } return(objRelease); }
private static async Task <IAsyncDisposable> TakeLockCoreAsync(DebuggableSemaphoreSlim objCurrentSemaphore, SafeSemaphoreRelease objRelease, CancellationToken token) { try { await objCurrentSemaphore.WaitAsync(token); } catch (OperationCanceledException) { //swallow this because it must be handled as a disposal in the original ExecutionContext } return(objRelease); }
private async Task <IAsyncDisposable> TakeWriteLockCoreAsync(DebuggableSemaphoreSlim objCurrentSemaphore, SafeWriterSemaphoreRelease objRelease) { await objCurrentSemaphore.WaitAsync(); if (Interlocked.Increment(ref _intCountActiveReaders) == 1) { try { // Wait for the reader lock only if there have been no other write locks before us if (_objTopLevelWriterSemaphore.CurrentCount != 0 || objCurrentSemaphore == _objTopLevelWriterSemaphore) { await _objReaderSemaphore.WaitAsync(); } } catch { Interlocked.Decrement(ref _intCountActiveReaders); throw; } } return(objRelease); }
private async ValueTask DisposeCoreAsync() { try { if (_objCurrentSemaphore.CurrentCount == 0) { await _objNextSemaphore.WaitAsync(); try { _objCurrentSemaphore.Release(); } finally { _objNextSemaphore.Release(); } } } finally { Utils.SemaphorePool.Return(ref _objNextSemaphore); } }
/// <summary> /// Heavier read lock entrant, used if a write lock is already being held somewhere /// </summary> private async Task TakeReadLockCoreAsync(DebuggableSemaphoreSlim objCurrentSemaphore, CancellationToken token = default) { await objCurrentSemaphore.WaitAsync(token); try { if (Interlocked.Increment(ref _intCountActiveReaders) == 1) { try { await _objReaderSemaphore.WaitAsync(token); } catch { Interlocked.Decrement(ref _intCountActiveReaders); throw; } } } finally { objCurrentSemaphore.Release(); } }
private static async Task <IAsyncDisposable> TakeLockCoreAsync(DebuggableSemaphoreSlim objCurrentSemaphore, SafeSemaphoreRelease objRelease) { await objCurrentSemaphore.WaitAsync(); return(objRelease); }