Reputation: 29668
I've found a rather strange issue and I don't understand why. My original intention was to use a mutex to prevent multiple instances of a console application from opening. To that end I had something like this:
[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
}
I would expect with this that if it cannot wait on the mutex, it will return immediately out of the Main()
method whilst honoring the finally block.
However, it appears I can run multiple instances with this code, it can always wait on the mutex and I always end up at the ReadKey()
point.
However, if I change the code to this:
[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();
}
}
Then this works as expected and only a single instance is allowed.
What I'm interested in is why the second code block works over the first, as far as I understood they should both work the same however they appear not to. Am I missing something obvious?
Upvotes: 0
Views: 109
Reputation: 28839
In your first example you create the mutex, wait on it, which will return immediately, then go on to destroy it, then wait for a key press. Since you destroyed the mutex, the next instance is not going to find it and will create it anew.
In your second example you keep the mutex around while waiting for the keypress thus preventing the second instance from starting.
Upvotes: 1