I have created simple MutexManager:
public static class MutexManager
{
private static string mutexName
{
get
{
return "MyAppName" + System.Security.Principal.WindowsIdentity.GetCurrent().User.AccountDomainSid;
}
}
public static bool CreateApplicationMutex()
{
bool createdNew;
var mutex = new Mutex(false, mutexName, out createdNew);
return createdNew;
}
}
The problem is that CreateApplicationMutex always returns true on new application instance startup. As long as I had exactly same code in app.cs everything was correct, but after I moved it to MutexManager createdNew is always true. What am I doing wrong?
The following works as expected for me, and returns false on second instance
public static class MutexManager
{
private static string mutexName => "MyAppName" + System.Security.Principal.WindowsIdentity.GetCurrent()
.User?.AccountDomainSid;
public static bool CreateApplicationMutex()
{
new Mutex(false, mutexName, out var createdNew);
return createdNew;
}
}
private static void Main(string[] args)
{
Console.WriteLine(MutexManager.CreateApplicationMutex());
Console.ReadKey();
}
Output
true
false
Make sure you debug your app, and check the mutex name
Winforms
MessageBox.Show(
MutexManager.CreateApplicationMutex()
.ToString());
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
WPF
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
MessageBox.Show(
MutexManager.CreateApplicationMutex()
.ToString());
base.OnStartup(e);
}
}
Once again it works as expected, and cant be reproduced
I had a similar problem, the reason was life time of mutex variable. Following code works fine by me in debug version, but always returns true for created_new in release version:
using System;
static class Program
{
[STAThread]
static void Main(string[] args)
{
string mutex_name = "MyApplicationName_SingleInstanceMutex";
bool created_new = false;
System.Threading.Mutex mutex = new System.Threading.Mutex(false, mutex_name, out created_new);
if (!created_new)
{
System.Windows.Forms.MessageBox.Show("Application is already started!");
return;
}
/* Create & run mainForm here */
}
}
Making mutex static solves the problem:
using System;
static class Program
{
static System.Threading.Mutex mutex = null;
[STAThread]
static void Main(string[] args)
{
string mutex_name = "MyApplicationName_SingleInstanceMutex";
bool created_new = false;
mutex = new System.Threading.Mutex(false, mutex_name, out created_new);
if (!created_new)
{
System.Windows.Forms.MessageBox.Show("Application is already started!");
return;
}
/* Create & run mainForm here */
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With