Using Mutex to restrict number of application instances
Symptoms
You have created an application (console application example given below) and if two instances were to run then they could interfere with each other.
Cause
Applications can be run multiple times in Windows. You must write your own restriction to prevent that from happening.
Resolution
A mutex (mutual exclusion object) is a program object that is created so that multiple program thread can take turns sharing the same resource, such as access to a file.
The mutex contructor below uses three parameters: bool initiallyOwned, string? name, out bool createdNew
- initiallyOwned - should the application request ownership of the mutex created.
- name - should be unique to this application but shared in all instances of the application, hence using the name of the containing assembly
- createdNew - indicates if the new mutex was successfully created. Will be false if the mutex of that name already exists.
`Question - will this work between different users logged in to the same machine?
internal class Program { private static Mutex mutex = null;
static void Main(string[] args)
{
string appName = Assembly.GetExecutingAssembly().GetName().Name;
bool createdNew;
mutex = new Mutex(true, appName, out createdNew);
if (createdNew == false)
{
var currentColour = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(appName + " is already running! Exiting the application.");
Console.ForegroundColor = currentColour;
return;
}
}
}