我应该处置互斥锁吗?
我正在开发 2 个 Windows 服务,它们有一个公共数据库,我想用系统互斥体锁定(跨进程)该数据库。
现在我想知道是否可以在 try-finally
块中调用 WaitOne()
和 ReleaseMutex()
还是我也应该处理互斥体(例如在 using
块中)。如果是这样,我想我应该总是在 WaitOne()
方法上捕获 AbandonedMutexException
,还是我错了?
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 call WaitOne()
and ReleaseMutex()
in a try-finally
block or should I also dispose the Mutex (e.g. in a using
block). If so I guess I should always catch the AbandonedMutexException
on the WaitOne()
method or am I wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
互斥锁是一个 Windows 内核对象(此处包装在 .NET 对象中)。
因此,它是一种应该被处置的非托管资源。
更准确地说,.NET 对象包含互斥锁的句柄,必须以某种方式释放/处置该互斥锁。
我不相信 Mutex 类文档中的代码示例 互斥对象未被释放。尽管 Henzi 在评论中提出了一个很好的观点:互斥对象是静态的,当进程退出时,它要么被终结器处理,要么被 Windows 内核销毁。
另请注意 关闭() 也处理该对象。
当然,即使您不使用现有的互斥对象,将其保留在应用程序中也没有什么问题。它们是轻资源。
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.
根据 this 一个名为
Mutex
会在以下情况下自动销毁:最后一个持有该互斥体HANDLE
的进程结束。在非托管术语 MSDN 中说
在 .NET 中,您应该调用
.Close()
- 这会释放Mutex
上的HANDLE
...因为每个进程在访问时都会获得自己的HANDLE
同名Mutex
这是一致的做法...一旦进程不再存在(终结器和所有),不调用Close()
不会留下任何问题...According to this a named
Mutex
is automatically destroyed when the last process holding aHANDLE
of that Mutex ends.In non-managed terms MSDN says
In .NET you should call
.Close()
on theMutex
- this releases theHANDLE
... since every process gets its ownHANDLE
when accessing even the same namedMutex
this is consistent practice... not callingClose()
won't leave any problems behing once the process is no more (finalizers and all)...您需要处置等待句柄使用的资源。
从文档中:
waithandle 使用非托管资源,应在使用结束时将其释放。
MSDN 文档互斥体
You need to dispose the resources which are used by the waithandle.
From the documentation:
The waithandle uses unmanaged resources which should be disposed at the end of use.
MSDN Documentation Mutex