Search code examples
c#multithreadingsynchronizationmutexdispose

Does .NET mutex engage unmanaged resources?


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()?


Solution

  • 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.