Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitor vs Mutex in c# [duplicate]

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#?

like image 498
Ajay Avatar asked Jul 22 '09 09:07

Ajay


People also ask

What is the difference between a mutex and a monitor?

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.

What is a monitor in C?

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.

What is the difference between lock and monitor in C#?

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.

What is the difference between a mutex A semaphore and a monitor and when would you use each?

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.


2 Answers

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.

like image 163
Marc Gravell Avatar answered Oct 06 '22 13:10

Marc Gravell


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.

like image 35
jpbochi Avatar answered Oct 06 '22 14:10

jpbochi