我发现了一个相当奇怪的问题,我不明白为什么。我的初衷是使用互斥锁来阻止打开控制台应用程序的多个实例。为此我有这样的事情:控制台互斥怪癖
[STAThread]
static void Main(string[] args)
{
// Attempt to create mutex
Mutex mutex = new Mutex(true,MUTEX_NAME);
try {
if (!mutex.WaitOne(0,true)) return;
...
} finally {
// Close mutex
mutex.Close();
}
// If debugging, allow for read-key pause
#if DEBUG
Console.ReadKey();
#endif
}
我希望这个,如果它不能互斥等待,它会立即返回了Main()
方法的同时履行finally块。
但是,看来我可以用这个代码运行多个实例,它可以随时等待互斥,我总是在ReadKey()
点结束。
不过,如果我更改代码这样:
[STAThread]
static void Main(string[] args)
{
// Attempt to create mutex
Mutex mutex = new Mutex(true,MUTEX_NAME);
try {
if (!mutex.WaitOne(0,true)) return;
...
// If debugging, allow for read-key pause
#if DEBUG
Console.ReadKey();
#endif
} finally {
// Close mutex
mutex.Close();
}
}
那么这个工作正常,只有一个实例是允许的。
我感兴趣的是什么,为什么第二个代码块工作在第一,据我了解,他们都应该工作一样的,但是他们似乎不。我错过了明显的东西吗?
这是什么MUTEX_NAME?它是一个共享互斥量吗? – 2013-02-22 00:27:25
@MarcGravell它被设置为'Global \ SDLP'。 – Lloyd 2013-02-22 10:06:13