更新时间: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:
的WaitOne
呼叫前转出。 AbanonedMutexException
。WaitOne
call.AbanonedMutexException
.