Skip to content

Fix NRE in AsyncReaderWriterLock.ReadLock method #2469

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

Merged
merged 1 commit into from
Aug 5, 2020
Merged
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
12 changes: 7 additions & 5 deletions src/NHibernate/Util/AsyncReaderWriterLock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,23 +82,23 @@ public async Task<Releaser> WriteLockAsync()

public Releaser ReadLock()
{
if (CanEnterReadLock())
if (CanEnterReadLock(out var waitingReadLockSemaphore))
{
return _readerReleaser;
}

_waitingReadLockSemaphore.Wait();
waitingReadLockSemaphore.Wait();

return _readerReleaser;
}

public Task<Releaser> ReadLockAsync()
{
return CanEnterReadLock() ? _readerReleaserTask : ReadLockInternalAsync();
return CanEnterReadLock(out var waitingReadLockSemaphore) ? _readerReleaserTask : ReadLockInternalAsync();

async Task<Releaser> ReadLockInternalAsync()
{
await _waitingReadLockSemaphore.WaitAsync().ConfigureAwait(false);
await waitingReadLockSemaphore.WaitAsync().ConfigureAwait(false);

return _readerReleaser;
}
Expand Down Expand Up @@ -165,14 +165,15 @@ private void ExitWriteLock()
}
}

private bool CanEnterReadLock()
private bool CanEnterReadLock(out SemaphoreSlim waitingReadLockSemaphore)
{
lock (_writeLockSemaphore)
{
AssertNotDisposed();
if (_writersWaiting == 0 && _writeLockSemaphore.CurrentCount > 0)
{
_currentReaders++;
waitingReadLockSemaphore = null;

return true;
}
Expand All @@ -183,6 +184,7 @@ private bool CanEnterReadLock()
}

_readersWaiting++;
waitingReadLockSemaphore = _waitingReadLockSemaphore;

return false;
}
Expand Down