Should I dispose a Mutex?

前端 未结 3 649
天命终不由人
天命终不由人 2020-12-10 12:24

I\'m working on 2 Windows Services that have a common database which I want to lock (cross-process) with a system Mutex.

Now I\'m wondering whether it\'s ok to just

3条回答
  •  有刺的猬
    2020-12-10 12:56

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

提交回复
热议问题