The code below is simplified, but it should get the point across. I
have an app that should only have one instance running at a time (it
interacts with hardware and moves files around, and doesn't work if
another instance is also doing that).
I thought I was accomplishing this by grabbing a named mutex at the
start. However, a very small number of times, a second instance of
the app manages to make it into the meat of the code (i.e., to the "Do
Stuff" comment), and I can't figure out how that's happening. Any
ideas?
using System;
using System.Collections.Generic;
using System.IO;
namespace TSSG.DeviceTesting
{
public sealed partial class TestEngine
{
[STAThread]
static public void Main(string[] commandLineArgs)
{
TestEngine te = new TestEngine();
te.RunApplication(commandLineArgs);
}
public void RunApplication(string[] commandLineArgs)
{
Mutex appExclusivityMutex = null;
bool gotMutex = false;
try
{
appExclusivityMutex = new Mutex(
false,
"Opsys Engine Exclusivity");
gotMutex = appExclusivityMutex.WaitOne(0, false);
if(!gotMutex)
{
MessageBox.Show(
"This application is already running.",
"Opsys Engine");
return;
}
// Do stuff. Problem is, sometimes we make it here
// with a different instance of the application ALSO
// running in this section of code. How is this
possible?
}
catch(Exception e)
{
}
finally
{
Cleanup();
if(gotMutex && null != appExclusivityMutex)
{
appExclusivityMutex.ReleaseMutex();
}
}
}
}
}
|