How can a lock statement be output without releasing the lock?

I have a strange problem, a deadlock problem, where if I pause the program using Visual Studio and check the threads, I can only see two threads waiting to be blocked. No thread is inside the blocking area! Is Visual Studio just false or how can a lock statement exit without releasing the lock?

thanks

+4
source share
4 answers

Do you have any explicit calls to Monitor.Enter / Monitor.TryEnter in your code? Can you see stack traces for these pending threads? If so, look where they are waiting - this should make it obvious.

+1
source

This may occur under the following circumstances. Suppose you have

 Enter(); try { Foo(); } finally { Exit(); } 

and a thread interruption exception is thrown after Enter, but before trying. Now the monitor has been introduced, but finally it will never be executed because an exception was thrown before the attempt.

We fixed this flaw in C # 4. In C # 4, the lock statement is now generated as

 bool mustExit = false; try { Enter(ref mustExit); Foo(); } finally { if (mustExit) Exit(); } 

Things can still go horribly wrong, of course; interruption of the thread does not guarantee that the thread is ever interrupted, which finally blocks the start-up and so on. You may end up in the unhandled exception handler with a locked lock. But it is at least a little better.

+9
source

This can happen if you manually call Monitor.Enter(something) without calling Monitor.Exit .

+2
source

Can you accidentally call a return income from a blocking instruction from a thread in a thread pool?

If so, you can see Concessive surprises

This blog post describes an error (I'm blocked) that I encountered when I combined these three things incorrectly. Fortunately, I decided to solve the problem with a little code change.

0
source

Source: https://habr.com/ru/post/1303687/


All Articles