using System; using System.Collections.Generic; using System.Threading;namespace ConsoleApplication1 { class Program { static Mutex mutex; static void Main(string[] args) { // // check whether 'MyMutex' is already created. if so, return immediately // bool createNew; mutex = new Mutex(false, "MyMutex", out createNew); if (!createNew) return; // // your code goes here // Console.WriteLine("I am the first and the only instance. Press enter to exit..."); Console.ReadLine(); } } } Putting a in the registry is not a good solution. If the program does not exit normally (for example being killed), the remains in the registry. And the program can't run anymore.In contrast, Mutex has a sense of ownership. When a process terminates, its ownership to the mutex is abandoned. Subsequent program has no problems to claim the mutex.
using System;
using System.Collections.Generic;
using System.Threading;namespace ConsoleApplication1
{
class Program
{
static Mutex mutex;
static void Main(string[] args)
{
//
// check whether 'MyMutex' is already created. if so, return immediately
//
bool createNew;
mutex = new Mutex(false, "MyMutex", out createNew);
if (!createNew) return; //
// your code goes here
//
Console.WriteLine("I am the first and the only instance. Press enter to exit...");
Console.ReadLine();
}
}
}
Putting a in the registry is not a good solution.
If the program does not exit normally (for example being killed), the remains in the registry.
And the program can't run anymore.In contrast, Mutex has a sense of ownership. When a process terminates, its ownership to the mutex is abandoned.
Subsequent program has no problems to claim the mutex.