Reputation: 2666
I understand how to force a single instance of an application using a mutex and this is what I use.
Several of my users have asked me to allow multiple instances to run. I don't want to remove the control code as I can see it as a recipe for disaster since multiple instances could be writing to the same files, log and so on.
I perhaps could handle things if the number of instances is limited to two. My current idea is to allow the first one to run as the active one and a second in some form of read-only mode.
So how would I control the number of instances to no more than two?
Thanks
Upvotes: 3
Views: 3211
Reputation: 164291
It sounds like you want a named system Semaphore with a count of 2.
Here is an example:
class Program
{
private const int MaxInstanceCount = 2;
private static readonly Semaphore Semaphore = new Semaphore(MaxInstanceCount, MaxInstanceCount, "CanRunTwice");
static void Main(string[] args)
{
if (Semaphore.WaitOne(1000))
{
try
{
Console.WriteLine("Program is running");
Console.ReadLine();
}
finally
{
Semaphore.Release();
}
}
else
{
Console.WriteLine("I cannot run, too many instances are already running");
Console.ReadLine();
}
}
}
A Semaphore allows a number of concurrent threads to access a resource, and when it is created with a name, it is a operating-system-wide semaphore, so it fits your purpose well.
Upvotes: 14
Reputation: 30097
bool IsFree = false;
Mutex mutex = new Mutex(true, "MutexValue1", out IsFree);
if(!IsFree)
mutex = new Mutex(true, "MutexValue2", out IsFree);
if(!IsFree)
{
//two instances are already running
}
Upvotes: 4