Occasionally you might want to create an application that can only have a single instance running on a machine at a time. For example, maybe you’ve a tray icon application or maybe an application that caches data for other applications to use etc.
We can achieve this by using a Mutex. A Mutex is very much like a Monitor/lock but can exist across multiple processes.
class Program { static void Main(string[] args) { using(Mutex mutex = new Mutex(false, "some_unique_application_key")) { if(!mutex.WaitOne(TimeSpan.FromSeconds(3), false)) { // another instance of the application must be running so exit return; } // Put code to run the application here } } }
So in the above code we create a mutex with a unique key (“some_unique_application_key”). It’s best to use something like a URL and application name, so maybe “putridparrot.com\MyApp” as an example. The mutex is held onto for the life of the application for obvious reasons.
Next we try to WaitOne, we need a timeout on this otherwise we’ll just block at this point until the other instance closes down (or more specifically the Mutex on the other instance is released). So choose a time span of your choice. If the timeout occurs then false is returned from WaitOne and we can take it that another instance of the application is running, so we exit this instance of the application.
On the other hand if (within the timeout) WaitOne returns true then no other instance of the application (well more specifically the named Mutex) exists and we can go ahead and do whatever we need to run our application.