C # - Benefits of System.Threading.Monitor for Thread Management

Since locking is an indirect representation of System.Threading.Monitor, if I want to use Monitor directly, I can get any additional benefits. (I read articles, he suggests always using Monitor for additional benefits. But there is no explanation of these advantages)

+4
source share
3 answers

Well, lock only calls Monitor.Enter and Monitor.Exit , so if you limit yourself to a lock you won’t be able to use other useful features like Monitor.Wait , Monitor.Pulse , etc. Otherwise, there is actually not any drawback to using lock instead of manually using Monitor.Enter and Monitor.Exit and lock really has the advantage that it automatically places the corresponding code in the fitting rooms, finally, the block.

+5
source

The lock statement is the syntax sugar in the Enter and Exit methods of the Monitor class.

You can use Pulse and Wait as follows:

 lock(x) { Monitor.Pulse(x); Monitor.Wait(x); } 

You should (at least as far as I know) use the monitor directly if you want to use the non-blocking TryEnter method.

I do not agree with the statement that you should always use Monitor ; The lock keyword is convenient when you just need to do what it offers.

+10
source

The Monitor class implements the monitor synchronization primitive: http://en.wikipedia.org/wiki/Monitor_%28synchronization%29 . As you can see, this is not a real .Net / C # idea, its well-known concept - it was taught as part of any computational degree. It offers you not only the ability to lock a critical section, but also provides the implementation of internal queries for a given instance, which allows a much more complex interaction between threads.

Regarding what you should use, the answer is usually the simplest method that does the job, which in> 90% of cases would just use the lock(sth){...} syntax.

+3
source

All Articles