Sometimes you need your application to have no more than one instance. Here comes the Mutex Class.
When two or more threads need to access a shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex.
Here is a simple example showing how you can control the instances of you application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
[STAThread] static void Main() { bool createdNew; Mutex mutex = new Mutex(true, "MyAppName", out createdNew); if (!createdNew) { Console.WriteLine("You cannot start more than one instance of this program!"); return; } Application.Run(new Form1()); GC.KeepAlive(mutex); } |
It’s very important to use GC.KeepAlive(mutex), because you want to hold the mutex as long as your application is running. If you omit this, the Garbage Collector may free this resource, when more memory is needed and when you try to start another instance of your application, you will succeed. Another variant is to use static variable for the mutex, but the second way is preferable.