开发者

Write lock being released without being held

开发者 https://www.devze.com 2023-04-12 04:33 出处:网络
I have a situation whereby ReadWriterLockSlim is throwing the exception \"System.Threading.SynchronizationLockException - The write lock is being released without being held.\" when I try to execute E

I have a situation whereby ReadWriterLockSlim is throwing the exception "System.Threading.SynchronizationLockException - The write lock is being released without being held." when I try to execute ExitWriteLock(). As far as I can tell, this shouldn't happen because subsequent threads that enter the try block will 'block' until they can obtain the lock. Am I missing something here?

The issue looks very similar to this one, however no solution was posted there.

//Code simplified for example. 

public class i18nService {
    internal static ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursi开发者_如何学Con);

    private string ProcessText()
    {
        try {
            cacheLock.EnterWriteLock();
            return "xyz";
        }
        finally {
            cacheLock.ExitWriteLock(); // Error is throwing here. 
        }
    }
}

Thanks very much for your help :-)


But if an error is thrown trying to enter the lock, then it will execute finally, without holding it. Why not simply change to:

...
finally {
    if(cacheLock.IsWriteLockHeld)
        cacheLock.ExitWriteLock();
}
...


    try {
        cacheLock.EnterWriteLock();
        return "xyz";
    }
    finally {
        cacheLock.ExitWriteLock(); // Error is throwing here. 
    }

Q: What happens if cacheLock.EnterWriteLock(); fails?

A: The finally statement gets executed.

  • cacheLock.ExitWriteLock(); gets called
  • But we don't have the lock

Try this:

private string ProcessText()
{
    cacheLock.EnterWriteLock();
    try {
        return "xyz";
    }
    finally {
        cacheLock.ExitWriteLock(); // Error is throwing here. 
    }
}

Presumably .NET is designed in such a way that if EnterWriteLock() fails, the lock is released (or never held at all).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号