Mutex does not prevent multiple app instances in release build?

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");
}
}
 
J

Jon Skeet [C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top