我应该配置一个互斥? [英] Should I dispose a Mutex?

查看:160
本文介绍了我应该配置一个互斥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作有哪些我想锁定(跨进程)与系统互斥通用数据库2的Windows服务。

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

现在我不知道是否它的确定只是叫 WaitOne的() ReleaseMutex()试戴最后块,或者我应该也配置互斥(例如,在使用块)。如果是的话我想我应该总是赶在 AbandonedMutexException WaitOne的()方法还是我错在这里?

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?

推荐答案

一个互斥体是Windows内核对象(这里,裹在.NET对象)。

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

因此​​,这是一个应该被设置在非托管资源。

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

更​​准确地说,.NET对象包含的句柄互斥体,它必须被释放/处置莫名其妙。

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

我不相信的在Mutex类文档代码示例其中互斥对象未设置。虽然亨齐在评论一个好点:互斥对象是静态的,将被终结或者被处置或销毁由Windows内核在进程退出时。

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.

这篇关于我应该配置一个互斥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆