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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With