Should I dispose a Mutex?

痞子三分冷 提交于 2019-11-28 10:58:23

A mutex is a Windows kernel object (here wrapped in a .NET object).

As such, it is an unmanaged resource that should be disposed.

More accurately, the .NET object contains a HANDLE to the mutex, which must be released/disposed of somehow.

I don't trust that code sample in the Mutex class docs where the mutex object is not disposed. Although Henzi has a good point in comment: The Mutex object is static and would be either disposed by the finalizer or destroyed by the Windows kernel when the process exits.

Also, note that Close() disposes the object as well.

Of course, there's nothing wrong with keeping an existing Mutex object in your app even while you don't use it. They are light resources.

According to this a named Mutex is automatically destroyed when the last process holding a HANDLE of that Mutex ends.

In non-managed terms MSDN says

Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The mutex object is destroyed when its last handle has been closed.

In .NET you should call .Close() on the Mutex - this releases the HANDLE... since every process gets its own HANDLE when accessing even the same named Mutex this is consistent practice... not calling Close() won't leave any problems behing once the process is no more (finalizers and all)...

You need to dispose the resources which are used by the waithandle.

From the documentation:

Releases all resources used by the current instance of the WaitHandle class. (Inherited from WaitHandle.)

The waithandle uses unmanaged resources which should be disposed at the end of use.

MSDN Documentation Mutex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!