Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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)

like image 486
user160677 Avatar asked Dec 02 '22 07:12

user160677


2 Answers

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.

like image 182
Paolo Tedesco Avatar answered Dec 21 '22 12:12

Paolo Tedesco


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.

like image 29
Joren Avatar answered Dec 21 '22 12:12

Joren