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

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

问题描述

我使用这个code至prevent我的程序的第二个实例从在同一时间运行的,是它的安全?

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.");
}

我很担心,如果事情抛出一个异常,应用程序崩溃互斥量仍将举行。是真的吗?

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.

首先要关闭互斥在最后块。否则,你的进程可能突然终止,让它在信号状态,像一个例外。这将让这个未来的流程实例不会将能够启动。

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.

但不幸的是,即使有最后块,你必须处理的过程将不会释放互斥体被终止的可能性。如果用户通过杀死的任务管理过程发生这种情况的实例。有一个在你的code的竞争条件,将允许在第二过程中获得的 AbandonedMutexException 的WaitOne 通话。你需要为这个恢复策略。

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.

我鼓励你阅读了关于 Mutex类的细节。使用它并不总是简单的。

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. 第二个进程启动并aquires的句柄,互斥,但的WaitOne 呼叫前转出。

  3. 进程#1突然终止。互斥锁不被破坏,因为进程#2有一个把手。它是不是设置为一个被遗弃的状态。

  4. 第二个进程重新开始运行,并得到一个 AbanonedMutexException

  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.

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

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