71

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

Community
  • 1
  • 1
Ajay
  • 9,947
  • 8
  • 32
  • 34
  • http://stackoverflow.com/questions/301160/what-are-the-differences-between-various-threading-synchronization-options-in-c – joe Jul 22 '09 at 09:14
  • I agree with using lock per default, but you need to call Monitor.Enter/Exit if 1) a timeout is needed or 2) if the locking scope is not restricted to a single method for some reason. – Brian Rasmussen Jul 22 '09 at 10:00
  • As an added note, Monitors provide what are often called "condition variables" with its Wait/Pulse methods. It allows one thread to wait for something until another thread call Pulse on the monitor. – nos Jan 19 '10 at 13:29

3 Answers3

51

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
25

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:

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.

jpbochi
  • 4,366
  • 3
  • 34
  • 43
19

A Mutex can be shared across processes, and is much more heavy-weight than a Monitor.

Use a Monitor unless you need to synchronize across process boundaries.

Kim Gräsman
  • 7,438
  • 1
  • 28
  • 41