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