When using ReaderWriterLock and ReaderWriterLockSlim for managing read and write locks, you should not release a read lock while holding a write lock and vice versa, otherwise you might have runtime exceptions. The locks should be always correctly paired so that the shared resource is accessed safely.
This rule raises if:
If you use the ReaderWriterLockSlim class, you will get a LockRecursionException. In the case of
ReaderWriterLock, you’ll get a runtime exception for trying to release a lock that is not owned by the calling thread.
Public Class Example
Private Shared rwLock As New ReaderWriterLock()
Public Sub Writer()
rwLock.AcquireWriterLock(2000)
Try
' ...
Finally
rwLock.ReleaseReaderLock() ' Noncompliant, will throw runtime exception
End Try
End Sub
Public Sub Reader()
rwLock.AcquireReaderLock(2000)
Try
' ...
Finally
rwLock.ReleaseWriterLock() ' Noncompliant, will throw runtime exception
End Try
End Sub
End Class
Public Class Example
Private Shared rwLock As New ReaderWriterLock()
Public Shared Sub Writer()
rwLock.AcquireWriterLock(2000)
Try
' ...
Finally
rwLock.ReleaseWriterLock()
End Try
End Sub
Public Shared Sub Reader()
rwLock.AcquireReaderLock(2000)
Try
' ...
Finally
rwLock.ReleaseReaderLock()
End Try
End Sub
End Class