Mutex
will work, but must be used correctly:
static void Main(string[] args)
{
bool createdNew;
Mutex mutex = new Mutex(true, "TestSO27835942", out createdNew);
if (createdNew)
{
Console.WriteLine("First process!");
}
else
{
Console.WriteLine("Second process...waiting for first process");
mutex.WaitOne();
Console.WriteLine("First process has completed");
}
Console.WriteLine("Press return to exit...");
Console.ReadLine();
mutex.ReleaseMutex();
}
This code creates or opens an existing named Mutex
. The first process to execute the code will create the Mutex
, and the createdNew
variable will be set to true
. The second (or any subsequent) process will simply open the existing named Mutex
, and the createdNew
variable will be set to false
.
Importantly, the first process will also acquire the Mutex
as part of the creation. This ensures that no other process can acquire the Mutex
before it. Then any subsequent process may attempt to acquire the Mutex
, which will can that process to wait until it's available.
Finally note that after the first process, there is no specific ordering. The first process, the one that gets to create the Mutex
, will always acquire it first. But after that, it just depends on how Windows schedules the processes. They will all get their turn though.