user160677
user160677

Reputation: 4303

C# - Advantages of System.Threading.Monitor to control thread

As lock is the indirect representation of System.Threading.Monitor ,incase if i wish to directly use the Monitor could i achieve any additional benefits.(I have read an articles ,it suggests always use Monitor to get additional benefits.But there is no explanation of those benefits)

Upvotes: 4

Views: 2187

Answers (3)

Paolo Tedesco
Paolo Tedesco

Reputation: 57202

The lock statement is syntactic sugar on the Enter and Exit methods of the Monitor class.

You can still use Pulse and Wait as follows:

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

You must (at least to my knowledge) use Monitor directly if you want to use the non-blocking TryEnter method.

I don't agree with the assertion that you should always use Monitor; the lock keyword is convenient when you just need to do what it offers.

Upvotes: 10

Joren
Joren

Reputation: 14746

Well, lock only calls Monitor.Enter and Monitor.Exit, so if you restrict yourself to lock you won't be able to use other useful features like Monitor.Wait, Monitor.Pulse, etc. Otherwise there isn't really any disadvantage to using lock instead of manually using Monitor.Enter and Monitor.Exit, and lock does have the advantage that it automatically puts the appropriate code in a try-finally block.

Upvotes: 5

Grzenio
Grzenio

Reputation: 36649

The Monitor class implements the monitor synchronization primitive: http://en.wikipedia.org/wiki/Monitor_%28synchronization%29. As you can see its not really .Net/C# idea, its widely known concept - taught as part of any Computing degree. It offers you not only ability to lock the critical section, but also provides implementation of queues internal for the given instance - which enables to have much more complicated interaction between threads.

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

Upvotes: 3

Related Questions