Possible Duplicate:
What are the differences between various threading synchronization options in C#?
What is the difference between a Monitor and a Mutex in C#?
When to use a Monitor and when to use a Mutex in C#?
The monitor lock only exist inside a single process, while the Mutex -lock is machine wide. So a monitor lock is appropriate for making objects and data-structures thread safe, but not for providing system-wide exclusive access to say a file or device.
In concurrent programming, a monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become false. Monitors also have a mechanism for signaling other threads that their condition has been met.
Both Monitor and lock provides a mechanism that synchronizes access to objects. lock is the shortcut for Monitor. Enter with try and finally. Lock is a shortcut and it's the option for the basic usage.
A mutex object allows multiple process threads to access a single shared resource but only one at a time. On the other hand, semaphore allows multiple process threads to access the finite instance of the resource until available. In mutex, the lock can be acquired and released by the same process at a time.
A Monitor
is managed, and more lightweight - but is restricted to your AppDomain
. A Mutex
can be named, and can span processes (allowing some simple IPC scenarios between applications), and can be used in code that wants a wait-handle).
For most simple scenarios, Monitor
(via lock
) is fine.
A good source of advice on this stuff is the "Threading in C#" by Joseph Albahari. All the content is available online. In my opinion, it's worth to read the whole book, but yo can check these parts:
On Locking (C# Monitor);
On Mutex.
Although it does not cover .NET 4.0 new parallel constructs, it's a very good starting point.
Update: The book has been updated. Now, it covers .NET 4.0 Parallel Programming in its part 5.
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