Single App Instance Enforcer - C#

A lot of desktop applications can only safely run, if there is only 1 instance running at a time.

This is especially true for non-scalable programs that need to perform a few operations, and were created with the assumption that there is no other instance running at the same time.

If a sys admin runs such a program and there is already an instance running, then there is a risk of data corruption (usually data duplication, as the same operations are performed more than once).

So here is a simple C# class that is used to check if there is another program instance running on the same machine.  If another instance is detected, then an ApplicationException is thrown.


 //the SingleApplicationInstanceEnforcer class 

 using System; 

 using System.Collections.Generic; 

 using System.Linq; 

 using System.Text; 

 using System.Threading; 

 using System.Diagnostics; 

 namespace Common.Utils 

 { 

   /// <summary> 

   /// prevent a 2nd instance of the application from running. 

   ///  

   /// Mutex is NOT safe to use, as it is complex how Windows goes about destroying the Mutex,  

   /// which could prevent application from running, even though there are no instances running. 

   /// </summary> 

   public class SingleApplicationInstanceEnforcer 

   { 

     //ref: http://stackoverflow.com/questions/646480/is-using-a-mutex-to-prevent-multipule-instances-of-the-same-program-from-running 

     static EventWaitHandle s_event; 

     public static void CheckIsOtherApplicationInstanceRunning(string applicationName) 

     { 

       if (s_event == null) 

       { 

         bool created; 

         s_event = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\" + applicationName + "#startup", out created); 

         if (!created) 

         { 

           s_event = null; 

           throw new ApplicationException("Another instance of this application is already running!"); 

         } 

       } 

     } 

   } 

 }  




here is sample code of a program checking for another instance running.


 //example code in a program, to check if there is another instance running: 

 // 

 //allow only 1 dev instance, only 1 live instance: 

 SingleApplicationInstanceEnforcer.CheckIsOtherApplicationInstanceRunning("my_app");  

Comments