This rule raises if you acquire a lock with one of the following methods, and do not release it within the same method.
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.
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.
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
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