So I have the following code:
...
private static void Main(string[] args)
{
string file=DateTime.Now.ToFileTime().ToString();
File.AppendAllText(file, "Mutex\r\n");
bool CreatedNew;
Mutex mutex=new Mutex(true, AppDomain.CurrentDomain.FriendlyName, out CreatedNew);
if(CreatedNew)
{
#if DEBUG
File.AppendAllText(file, "Launching in DEBUG mode\r\n");
#else
File.AppendAllText(file, "Launching in RELEASE mode\r\n");
#endif
//Program.Launch();
Program.ProcessArgsAndLaunch(args);
}
else
{
File.AppendAllText(file, "Handling dupe\r\n");
Program.HandleDuplicate();
}
}
...
I've checked innumerable articles here and other sites with no luck.
Basically, the code checks for a running instance of the app and if there is one, it switches to the main window of the running one. If not, it launches the app.
In Debug
mode it all works as expected, the problem starts when I switch my configuration to Release
: the app always starts (with Mutex
seemingly doing nothing).
I've added conditionally compiled dumps that show in which mode the app is starting and the output changes based on the configuration, but sadly, so does the behaviour of the app.
This may be a race condition
but I am not sure.
More code will be posted if needed.
Thanks.
Along with Juan's answer, there's a difference in terms of garbage collection between launching inside and outside a debugger. That's not quite the same as a Debug configuration vs a Release configuration, but it's something you should be aware of anyway.
In the debugger, a local variable will act as a GC root for its entire scope - but when you're not debugging, your mutex
variable isn't a GC root at all, because you don't use it after initializing it. That means your Mutex
can be garbage collected (and thus the native mutex will be released) pretty much immediately.
You should use a using
statement to explicitly dispose the Mutex
at the right time:
// Note that you don't need a variable here... you can have one if you
// want though
using (new Mutex(...))
{
// Code here to be executed while holding the mutex
}
See more on this question at Stackoverflow