Allow Only One Instance

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.

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.