Are there any circumstances under which a call to EnterWriteLock on ReaderWriterLockSlim should introduce a read lock?

I have a seemingly very simple case when I use System.Threading.ReaderWriterLockSlim in version 3.5 of the .NET Framework. I first declare one, as shown here:

Block ad http://odeh.temp.s3.amazonaws.com/lock_declaration.bmp

I set a breakpoint right before the lock is received, and take a screenshot so that you can see (in the clock window) that the locks are not currently locked:

preliminary blocking http://odeh.temp.s3.amazonaws.com/prelock.bmp

Then after calling EnterWriteLock, as you can see, I hold Read Lock .

after blocking http://odeh.temp.s3.amazonaws.com/postlock.bmp

This seems really unexpected behavior, and I can't find it documented anywhere. Does anyone else know why this is happening? Elsewhere in my code (earlier), this exact same line of code correctly gets a write lock. However, sequentially on several systems, instead, it gets a read lock at this point in the call stack. Hope I made it clear and thank you for taking the time to look at it.

--- EDIT ---

For those who mention statements ... this only confuses me:

post assert http://odeh.temp.s3.amazonaws.com/assert.bmp

I really can’t say how this statement went, except that the Watch window and the Immediate window may be wrong (maybe the value is stored in a local stream, as mentioned in another poster). This seems like an obvious case for a mutable variable, and setting the Happens Before should be set. In any case, a few lines later there is code that claims to be write-locked and does not have it. I set a breakpoint on the only line of code in the entire program that releases this lock, and it does not get called after it is shown here, so this should mean that it was never acquired ... right?

+4
source share
1 answer

This may be a side effect of the debugger. The ReaderWriterLockSlim class is very sensitive to the current thread identifier (Thread.ManagedThreadId). I cannot argue that the debugger will always use the current active thread to evaluate clock expressions. This usually happens, but there may be other behavior, say, if you entered a debugger with a hard break.

Trust what the code does first, your Debug.Assert proves the point.

+2
source

All Articles