Mutex does not prevent multiple app instances in release build?

  • Thread starter Thread starter Ed Sutton
  • Start date Start date
E

Ed Sutton

I am using a mutex to prevent a user from starting multiple application
instances.

This works fine in debug. Does anyone have any ideas why the following
code would not work in a release build?

I start an instance of the executable from the release directory, then I
start a second instance, and firstInstance is always true.

Thanks in advance,
-Ed

[STAThread]
static void Main()
{
try
{
// Check if an instance of the app. exists
bool firstInstance = false;
string safeName = Application.UserAppDataPath.Replace(@"\","_");
Mutex mutex = new Mutex(true, safeName, out firstInstance);
if(false == firstInstance)
{
return;
}
Application.Run(new FrmMain());
}
catch(Exception ex)
{
Err.Show(ex, "Caught an unexpected exception in FrmMain");
}
}
 
Ed Sutton said:
I am using a mutex to prevent a user from starting multiple application
instances.

This works fine in debug. Does anyone have any ideas why the following
code would not work in a release build?

Yes. I believe the mutex is being garbage collected.

If you put a:

GC.KeepAlive (mutex);

*after* your call to Application.Run, I believe the problem will go
away.
 
Back
Top