[英]Should I dispose a Mutex?
I'm working on 2 Windows Services that have a common database which I want to lock (cross-process) with a system Mutex. 我正在开发2个Windows服务,它有一个公共数据库,我想用系统Mutex锁定(交叉处理)。
Now I'm wondering whether it's ok to just call WaitOne()
and ReleaseMutex()
in a try-finally
block or should I also dispose the Mutex (eg in a using
block). 现在我想知道在
try-finally
块中调用WaitOne()
和ReleaseMutex()
,或者我是否也应该using
Mutex(例如在using
块中)。 If so I guess I should always catch the AbandonedMutexException
on the WaitOne()
method or am I wrong here? 如果是这样我想我应该总是在
WaitOne()
方法上捕获AbandonedMutexException
,或者我在这里错了?
A mutex is a Windows kernel object (here wrapped in a .NET object). 互斥锁是Windows内核对象(此处包含在.NET对象中)。
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. 更准确地说,.NET对象包含互斥锁的HANDLE,必须以某种方式释放/处理。
I don't trust that code sample in the Mutex class docs where the mutex object is not disposed. 我不相信Mutex类docs中没有处理互斥对象的代码示例 。 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.
虽然Henzi在评论中有一个很好的观点:Mutex对象是静态的,并且在进程退出时由终结器处理或由Windows内核销毁。
Also, note that Close() disposes the object as well. 另请注意, Close()也会处理对象。
Of course, there's nothing wrong with keeping an existing Mutex object in your app even while you don't use it. 当然,即使您不使用它,在应用程序中保留现有Mutex对象也没有错。 They are light resources.
它们是轻资源。
According to this a named Mutex
is automatically destroyed when the last process holding a HANDLE
of that Mutex ends. 根据这个名称,当持有该互斥锁的
HANDLE
的最后一个进程结束时,一个命名的Mutex
会自动销毁。
In non-managed terms MSDN says MSDN表示,在非托管条款中
Use the
CloseHandle
function to close the handle.使用
CloseHandle
函数关闭句柄。 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)... 在.NET中,您应该在
Mutex
上调用.Close()
- 这会释放HANDLE
...因为每个进程在访问同一个名为Mutex
时都会获得自己的HANDLE
这是一致的做法...不会调用Close()
一旦流程不复存在,就会留下任何问题(终结者和所有人)......
You need to dispose the resources which are used by the waithandle. 您需要处理waithandle使用的资源。
From the documentation: 从文档:
Releases all resources used by the current instance of the WaitHandle class.
释放WaitHandle类的当前实例使用的所有资源。 (Inherited from WaitHandle.)
(继承自WaitHandle。)
The waithandle uses unmanaged resources which should be disposed at the end of use. waithandle使用非托管资源,应在使用结束时进行处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.