-1

MSDN article Mutex Class tells (in comments to code example):

Unlike Monitor, Mutex can be used with WaitHandle.WaitAll and WaitAny, and can be passed across AppDomain boundaries

Does it mean that mutexes employ unmanaged resurces?
Why, then, the MSDN code example on Mutex usage does not use Dispose()?

Fulproof
  • 4,466
  • 6
  • 30
  • 50
  • 1
    http://stackoverflow.com/questions/7107079/should-i-dispose-a-mutex – adt Mar 01 '13 at 09:30
  • Does the documentation mention anything ?. If the `Mutex` class "engages" unmanaged resources or not can either be part of the convention if proposes, or not. If it is not part of the convention then it's best to believe that the implementation details might change someday (and that the answer to this question might not be immutable throughout the entire life of the .NET BCL) and not to base your architectural decisions on that current status quo. Regarding `IDisposable`. There are many examples of classes that "engage" unmanaged resources and that don't do that either (for instance: `Thread`) – Eduard Dumitru Mar 01 '13 at 09:33
  • `Mutex` implements `IDisposable`, therefore you call `Dispose`. Documentation takes precedence over a code sample that's been trimmed down to illustrate a concept. – anton.burger Mar 01 '13 at 09:34

2 Answers2

2

Mutex and many other synchronization objects are wrappers around different kernel objects (http://msdn.microsoft.com/en-us/library/windows/desktop/ms724485(v=vs.85).aspx), so yes, they use unmanaged resources under the hood.

You should call .Dispose when you are done with them, however, they will be freed when your process exits or when finalizer with launch (if you have not disposed them), so I guess, that for simplicity of examples they just did not Dispose them properly.

Note from MSDN about WaitHandles:

Always call Dispose before you release your last reference to the WaitHandle. 
Otherwise, the resources it is using will not be 
freed until the garbage collector calls the WaitHandle object's Finalize method.
Marcin Deptuła
  • 11,789
  • 2
  • 33
  • 41
0

Yes, you should dispose Mutex as it inherits WaitHandle that implements IDisposable.

Internally, Mutex is a wrapper for a kernel object created by the CreateMutext. I suppose the Dispose implementation of the .Net Mutex class calls CloseHandle to close the kernel object handle.

In any case, such an handle will be automatically closed by the system when the process exits.

ken2k
  • 48,145
  • 10
  • 116
  • 176