If you use the ReaderWriterLockSlim
class, you will get a LockRecursionException. In the case of
ReaderWriterLock
, you’ll get a runtime exception for trying to release a lock that is not owned by the calling thread.
Code examples
Noncompliant code example
public class Example
{
private static ReaderWriterLock rwLock = new();
public void Writer()
{
rwLock.AcquireWriterLock(2000);
try
{
// ...
}
finally
{
rwLock.ReleaseReaderLock(); // Noncompliant, will throw runtime exception
}
}
public void Reader()
{
rwLock.AcquireReaderLock(2000);
try
{
// ...
}
finally
{
rwLock.ReleaseWriterLock(); // Noncompliant, will throw runtime exception
}
}
}
Compliant solution
public class Example
{
private static ReaderWriterLock rwLock = new();
public static void Writer()
{
rwLock.AcquireWriterLock(2000);
try
{
// ...
}
finally
{
rwLock.ReleaseWriterLock();
}
}
public static void Reader()
{
rwLock.AcquireReaderLock(2000);
try
{
// ...
}
finally
{
rwLock.ReleaseReaderLock();
}
}
}