是否使用互斥锁来防止同一程序的多个实例安全运行? [英] Is using a Mutex to prevent multiple instances of the same program from running safe?

查看:33
本文介绍了是否使用互斥锁来防止同一程序的多个实例安全运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码来防止我的程序的第二个实例同时运行,是否安全?

I'm using this code to prevent a second instance of my program from running at the same time, is it safe?

Mutex appSingleton = new System.Threading.Mutex(false, "MyAppSingleInstnceMutx");
if (appSingleton.WaitOne(0, false)) {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MainForm());
    appSingleton.Close();
} else {
    MessageBox.Show("Sorry, only one instance of MyApp is allowed.");
}

我担心如果出现异常并且应用程序崩溃,Mutex 仍将被保留.是真的吗?

I'm worried that if something throws an exception and the app crashes that the Mutex will still be held. Is that true?

推荐答案

总的来说,是的,这会起作用.然而,魔鬼在细节中.

In general yes this will work. However the devil is in the details.

首先,您要在 finally 块中关闭互斥锁.否则,您的进程可能会突然终止并使其处于有信号状态,例如异常.这将使未来的流程实例无法启动.

Firstly you want to close the mutex in a finally block. Otherwise your process could abruptly terminate and leave it in a signaled state, like an exception. That would make it so that future process instances would not be able to start up.

不幸的是,即使使用 finally 块,您也必须处理进程将在不释放互斥锁的情况下终止的可能性.例如,如果用户通过 TaskManager 终止进程,就会发生这种情况.您的代码中存在竞争条件,这将允许第二个进程在 WaitOne 调用中获得 AbandonedMutexException.为此,您需要一个恢复策略.

Unfortunately though, even with a finally block you must deal with the potential that a process will be terminated without freeing up the mutex. This can happen for instance if a user kills the process through TaskManager. There is a race condition in your code that would allow for a second process to get an AbandonedMutexException in the WaitOne call. You'll need a recovery strategy for this.

我鼓励您阅读有关互斥锁的详细信息类.使用它并不总是那么简单.

I encourage you to read up on the details of the Mutex class. Using it is not always simple.

扩展竞争条件的可能性:

Expanding upon the race condition possibility:

以下事件序列可能会导致应用程序的第二个实例抛出:

The following sequence of events can occur which would cause a second instance of the application to throw:

  1. 正常进程启动.
  2. 第二个进程启动并获取互斥锁的句柄,但在 WaitOne 调用之前被关闭.
  3. 进程 #1 突然终止.互斥体不会被销毁,因为进程 #2 有一个句柄.它被设置为废弃状态.
  4. 第二个进程再次开始运行并得到一个 AbannedMutexException.
  1. Normal process startup.
  2. Second process starts up and aquires a handle to the mutex but is switched out before the WaitOne call.
  3. Process #1 is abruptly terminated. The mutex is not destroyed because process #2 has a handle. It is instead set to an abandoned state.
  4. The second process starts running again and gets an AbanonedMutexException.

这篇关于是否使用互斥锁来防止同一程序的多个实例安全运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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