1

Possible Duplicate:
Monitor vs Mutex in c#

Hi,

In this site i found different different answers from different people which makes confusing. still not at all clear exactly on which scenario each of the three terms [Lock,Monitor,Mutex] will be very useful for the realtime need. Makes much more confusion between these terms.

I would require very clear differences in High level-in depth and which is essentially required to use among each of the three terms with better example and with clear understanding.

Kindly provide the info at the very high level of realtime usage or need using C#.NET with very good example.

Thanks Sukumar

Community
  • 1
  • 1
Sukumar
  • 21
  • 1
  • 2
  • 1
    This question had pretty clear answers: http://stackoverflow.com/questions/1164038/monitor-vs-mutex-in-c – Rob Nov 19 '09 at 13:23
  • This question's answers are also quite clear: http://stackoverflow.com/questions/301160/what-are-the-differences-between-various-threading-synchronization-options-in-c – Rob Nov 19 '09 at 13:25

2 Answers2

9

Simplified and in short:

A Monitor is the managed .NET synchronization primitive (scope is one application domain only). The C# lock() does nothing but use Monitor and a try...finally clause to make sure that the lock is released in the case of an exception.

A Mutex is an OS synchronization object, which can also be used to synchronize across multiple processes (via named mutex).

Lucero
  • 59,176
  • 9
  • 122
  • 152
  • 3
    +1 for lock internally uses Monitor try finally http://msdn.microsoft.com/en-us/library/ms173179(VS.80).aspx "Using the lock keyword is generally preferred over using the Monitor class directly, both because lock is more concise, and because lock insures that the underlying monitor is released, even if the protected code throws an exception." MSDN – PRR Nov 19 '09 at 13:57
4
  • A 'Lock' is a general term, could mean several things
  • the locks statement, lock(x) { } uses the Monitor class
  • the Monitor class is a (relatively) lightweight mutex class. It is fully build in managed code and needs no interaction with WIN32 API's
  • A Mutex is a Win32 class. Named Mutexes can be useful to sync across applications, but otherwise use Monitor.
  • You forgot ResetEvents and Waithandles
H H
  • 263,252
  • 30
  • 330
  • 514