microsoft / referencesource

Source from the Microsoft .NET Reference Source that represent a subset of the .NET Framework
https://referencesource.microsoft.com/
MIT License
3.16k stars 1.27k forks source link

ReaderWriterLockSlim reports inncorrect RecursiveReadCount in debugger. #90

Closed DonaldAirey closed 5 years ago

DonaldAirey commented 5 years ago

I'm creating a transaction. At the end of the transaction, I release any locks on the object. Based on the data encountered, the application may have taken an Upgradable Read Lock and promoted it to a Write Lock, so I'm never guaranteed to know what state the lock is in at the end of the transaction. I have the following logic to deal with this scenario:

        public ReaderWriterLockSlim Lock { get; } = new ReaderWriterLockSlim();

        private void OnTransactionCompleted(object sender, TransactionEventArgs transactionEventArgs)
        {
            if (this.Lock.IsReadLockHeld)
            {
                this.Lock.ExitReadLock();
            }
            if (this.Lock.IsWriteLockHeld)
            {
                this.Lock.ExitWriteLock();
            }
            if (this.Lock.IsUpgradeableReadLockHeld)
            {
                this.Lock.ExitUpgradeableReadLock();
            }
        }

Using this outline, I've noticed that the debugger is giving me false indications that a Read lock is active on this object after running this code. I've placed Assert statements (asserting that there's no reader lock), and they haven't been tripped, but the debugger is adamant that the RecursiveReadCount is 1 and a Read lock is held.

In researching this, I came across several old articles claiming that we shouldn't use the IsReadLockHeld property except in Asserts and debugging. So I have two issues: #1, the debugger is clearly giving me a false indication and #2, is this pattern valid? If not, how are we supposed to release the locks when we don't have a guarantee that they've been locked (like with an Upgraded Read lock in a transaction)?

svick commented 5 years ago

This repository is not the right place to report issues or ask questions about .Net Framework.

If you want to report an issue, the right place is the .Net Developer Community.

If you want to ask a question, I think the best place is Stack Overflow.

terrajobst commented 5 years ago

This repo only tracks infrastructure issues regarding the following items:

For issues regarding functionality, please use the following resources: