Why is this an issue?
If a lock is held or acquired and then released within a method, it should be released along all execution paths.
Failing to do so could make an application deadlock-prone because there is a risk of the lock not being released.
The types tracked by the rule are: Monitor
, Mutex
, ReaderWriterLock
, ReaderWriterLockSlim
, and
SpinLock
from the System.Threading
namespace.
This rule raises an issue when a lock is acquired in a method but only released on some paths. No issue is raised when the lock is never released
in the method. The assumption is that callers will release it.
Noncompliant code example
Class Example
Private obj As Object = New Object()
Public Sub DoSomethingWithMonitor()
Monitor.Enter(obj) ' Noncompliant
If IsInitialized() Then
' ..
Monitor.Exit(obj)
End If
End Sub
Private lockObj As ReaderWriterLockSlim = New ReaderWriterLockSlim()
Public Sub DoSomethingWithReaderWriteLockSlim()
lockObj.EnterReadLock() ' Noncompliant
If IsInitialized() Then
' ..
lockObj.ExitReadLock()
End If
End Sub
End Class
Compliant solution
Class Example
Private obj As Object = New Object()
Public Sub DoSomethingWithMonitor()
SyncLock obj ' is easier to use than explicit Monitor calls
If IsInitialized() Then
End If
End SyncLock
End Sub
Private lockObj As ReaderWriterLockSlim = New ReaderWriterLockSlim()
Public Sub DoSomethingWithReaderWriteLockSlim()
lockObj.EnterReadLock()
Try
If IsInitialized() Then
End If
Finally
lockObj.ExitReadLock()
End Try
End Sub
End Class
Resources