这是正确使用互斥? [英] Is this the proper use of a mutex?

查看:156
本文介绍了这是正确使用互斥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个情况我可能有一个程序运行的多个实例一次,而且重要的是,只是一个特定的功能不会一下子在这些情况下的多个执行。



这是使用一个互斥体,以防止这种情况发生的正确方法?

 锁(this.GetType ()){
_log.Info(做同步);
DoSync();
_log.Info(同步完成);
}


解决方案

您说了的多个实例应用程序,因此我们正在谈论大约两Program.exe文件的运行,对不对? lock语句不会跨越多个程序锁定,只是在程序中。如果你想有一个真正的互斥,看 System.Threading.Mutex 对象



下面是一个使用示例:

 布尔createdNew;使用(互斥MTX =新的Mutex(false,那么MyAwesomeMutex,出createdNew))
{

{
mtx.WaitOne()
;

MessageBox.Show(点击确定释放互斥锁。);
}
终于
{
mtx.ReleaseMutex();
}
}



createdNew变量将让你知道它是否创建的第一次。它只是告诉你,如果已经创造了它,虽然。如果你想要获取的锁,你需要调用WaitOne的,然后调用ReleaseMutex来释放它。如果你只是想看看你是否创建一个互斥,只是构建它是好的。


I have a situation where I might have multiple instances of a program running at once, and it's important that just one specific function not be executing in more than one of these instances at once.

Is this the proper way to use a mutex to prevent this from happening?

lock (this.GetType()) {
    _log.Info("Doing Sync");
    DoSync();
    _log.Info("Sync Completed");
}

解决方案

You said multiple instances of one application, so we're talking about two program.exe's running, right? The lock statement won't lock across multiple programs, just within the program. If you want a true Mutex, look at the System.Threading.Mutex object.

Here is a usage example:

bool createdNew;
using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew))
{
    try
    {
        mtx.WaitOne();

        MessageBox.Show("Click OK to release the mutex.");
    }
    finally
    {
        mtx.ReleaseMutex();
    }
}

The createdNew variable will let you know whether or not it was created the first time. It only tells you if it has been created, though. If you want to acquire the lock, you need to call WaitOne and then call ReleaseMutex to release it. If you just want to see if you created a Mutex, just constructing it is fine.

这篇关于这是正确使用互斥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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