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 static ReaderWriterLock rwLock = new();
public void AcquireWriterLock() =>
rwLock.AcquireWriterLock(2000); // Noncompliant, as the lock release is on the callers responsibility
public void DoSomething()
{
// ...
}
public void ReleaseWriterLock() =>
rwLock.ReleaseWriterLock();
}
Compliant solution
public class Example
{
private static ReaderWriterLock rwLock = new();
public void DoSomething()
{
rwLock.AcquireWriterLock(2000); // Compliant, locks are released in the same method
try
{
// ...
}
finally
{
rwLock.ReleaseWriterLock();
}
}
}