
org.sonar.plugins.vbnet.S7133.html Maven / Gradle / Ivy
This rule raises if you acquire a lock with one of the following methods, and do not release it within the same method.
- ReaderWriterLock.AcquireReaderLock
- ReaderWriterLock.AcquireWriterLock
- ReaderWriterLockSlim.EnterReadLock
- ReaderWriterLockSlim.EnterUpgradeableReadLock
- ReaderWriterLockSlim.TryEnterReadLock
- ReaderWriterLockSlim.TryEnterUpgradeableReadLock
- ReaderWriterLockSlim.EnterWriteLock
- ReaderWriterLockSlim.TryEnterWriteLock
- SpinLock.Enter
- SpinLock.TryEnter
This rule will raise an issue when the code uses the disposable pattern. This pattern makes locking
easy to use and delegates the responsibility to the caller. Users should accept issues in such cases, as they should appear only once for each
synchronization type.
Why is this an issue?
Not releasing a lock in the same method where you acquire it, and releasing in another one, makes the code less clear and harder to maintain. You
are also introducing the risk of not releasing a lock at all which can lead to deadlocks or exceptions.
Code examples
Noncompliant code example
Public Class Example
Private Shared rwLock As New ReaderWriterLock
Public Sub AcquireWriterLock()
rwLock.AcquireWriterLock(2000) ' Noncompliant, as the lock release is on the callers responsibility
End Sub
Public Sub DoSomething()
' ...
End Sub
Public Sub ReleaseWriterLock()
rwLock.ReleaseWriterLock()
End Sub
End Class
Compliant solution
Public Class Example
Private Shared rwLock As New ReaderWriterLock
Public Sub DoSomething()
rwLock.AcquireWriterLock(2000) ' Compliant, locks are released in the same method
Try
' ...
Finally
rwLock.ReleaseWriterLock()
End Try
End Sub
End Class
Resources
Documentation
- Microsoft Learn - ReaderWriterLock Class
- Microsoft Learn - ReaderWriterLockSlim Classs
- Microsoft Learn - SpinLock Struct
© 2015 - 2025 Weber Informatics LLC | Privacy Policy