none
ReaderWriterLockSlim.TryEnterWriteLock returns true but ReaderWriterLockSlim.ExitWriteLock throws exception "The write lock is being released without being held." RRS feed

  • Question

  • I've seen this bug happen randomly in production code and have been able to somewhat more reliably recreate this error with some test code.  Essentially I am aquiring a write lock using ReaderWriterLockSlim.TryEnterWriteLock.  In some cases, the method returns true, but when ReaderWriterLockSlim.ExitWriteLock executes, it throws a SynchronizationLockException saying "The write lock is being released without being held".

    Here's my test lock code:
            public void ExecuteInWriteLock(Action writeCode) 
            { 
                bool gotLock = Lock.TryEnterWriteLock(DefaultTimeout); 
                if (!gotLock) 
                    throw new TimeoutException("Timeout expired trying to enter write lock"); 
                try { writeCode(); } 
                finally 
                { 
                    try { Lock.ExitWriteLock(); } 
                    catch 
                    { 
                        Console.WriteLine("Got lock: " + gotLock); 
                        throw; 
                    } 
                } 
            } 


    Under what condition(s) would I get true when a lock doesn't really exist?  I have a screenshot of it happening as well, but not sure how to attach that.


    Monday, October 20, 2008 4:58 PM

All replies

  • You can't. It simply is not possible.  How is ExecuteInWriteLock being called? You didn't say.  post a sketch of WriteCode as well. I think your code is racing.
    Saturday, November 15, 2008 2:17 PM