This rule raises if you acquire a lock with one of the following methods, and do not release it within the same method.

- ReaderWriterLock.AcquireReaderLock
- ReaderWriterLock.AcquireWriterLock
- ReaderWriterLockSlim.EnterReadLock
- ReaderWriterLockSlim.EnterUpgradeableReadLock
- ReaderWriterLockSlim.TryEnterReadLock
- ReaderWriterLockSlim.TryEnterUpgradeableReadLock
- ReaderWriterLockSlim.EnterWriteLock
- ReaderWriterLockSlim.TryEnterWriteLock
- SpinLock.Enter
- SpinLock.TryEnter

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.

## Why is this an issue?

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();
            }
        }
    }

## Resources

### Documentation

- Microsoft Learn - ReaderWriterLock Class
- Microsoft Learn - ReaderWriterLockSlim Classs
- Microsoft Learn - SpinLock Struct