I have a .net 3.5 / c# / wpf app that I don't want users to be able to run multiple instances of. So I use the following in my app.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
const string mutexName = "Local\\MyApp.SingleInstance";
try
{
// Create a new mutex object with a unique name
_mutex = new Mutex(false, mutexName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace +
"\n\n" + "Application Exiting…", "Exception thrown");
Current.Shutdown();
}
if (_mutex.WaitOne(0, false))
{
base.OnStartup(e);
}
else
{
MessageBox.Show("app is already open", "Error", MessageBoxButton.OK, MessageBoxImage.Information);
Current.Shutdown();
}
//...show mainwindow or load app
}
My problem is that some of my users report this exception: Exception: The wait completed due to an abandoned mutex. Type: System.Threading.AbandonedMutexException
I can't reproduce this locally, so it's hard for me to figure out what is happening.
Would adding
finally
{
_mutex.ReleaseMutex();
}
After my try/catch possibly help?