且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是互斥来prevent同一个程序的多个实例运行安全吗?

更新时间:2023-11-22 20:44:04

在总体肯定这会工作。然而,魔鬼在细节。

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.