How to Restrict the Application to Just One Instance

There are certain circumstances when you need to allow your application to run just once. Such requirement usually depends on the scenario you're currently working on. One of the most common reasons to limit the number of instances is to restrict the access to some sensitive resources.

For this purpose, we use the Mutex object. This approach can be used on all three types of desktop applications (console, winforms, WPF). A Mutex (mutual exclusion) is an object (or principle if you want) that is commonly used for synchronizing several threads when they are accessing and using the same resources. It is sort of a gate keeper that allows just one visitor to enter the code at a time. You can check WikiPedia to better understand this principle: Mutial exclusion.

Even though the same principle can be used in all three types of desktop applications, there are minor differences among them. To be more specific, you need to find the proper entry point where the Mutex will be used.

Also, there is a slight chance that the mutex could go out of scope and get garbage collected, so we need to make it either static or call GC.KeepAlive(mutex) to prevent the collection. In the examples below, the first approach (static class) is being used.

Now let me go through each type to show the usage.

Console Application

The entry point of a console application is the Main method. When we run the application, a Mutex object with a unique identifier (the appName in this case) is created. The constructor takes 3 arguments, with the 3rd being the most important. This output parameter simply tells us whether other objects with the same identifier was already created. If so, other instances of our application is already running, so we need to close the current instance.

  1. class Program  
  2.     {  
  3.         private static Mutex mutex = null;
  4.         
  5.         static void Main(string[] args)  
  6.         {  
  7.             const string appName = "MyAppName";  
  8.             bool createdNew;  
  9.   
  10.             mutex = new Mutex(true, appName, out createdNew);  
  11.   
  12.             if (!createdNew)  
  13.             {  
  14.                 Console.WriteLine(appName + " is already running! Exiting the application.");  
  15.                 Console.ReadKey();  
  16.                 return;  
  17.             }  
  18.   
  19.             Console.WriteLine("Continuing with the application");  
  20.             Console.ReadKey();  
  21.         }  
  22.     }  

Windows Forms Applications

In Windows Forms applications, the approach is nearly the same. The entry point of the application is usually the Main method in the static Program class.

  1. [STAThread]                    
  1.         private static Mutex mutex = null;

  2.         static void Main()  
  3.         {  
  4.             const string appName = "MyAppName";  
  5.             bool createdNew;  
  6.   
  7.             mutex = new Mutex(true, appName, out createdNew);  
  8.   
  9.             if (!createdNew)  
  10.             {  
  11.                //app is already running! Exiting the application  
  12.                 return;  
  13.             }  
  14.   
  15.             Application.EnableVisualStyles();  
  16.             Application.SetCompatibleTextRenderingDefault(false);  
  17.             Application.Run(new Form1());  
  18.         }  

WPF

Using a Mutex in WPF is a little trickier, but still easily achievable. The entry point of a WPF app is the App.xml.cs (a code behind file of App.xaml) and we need to override the OnStartup method to properly exit the application right after the start if needed.

  1. public partial class App : Application  
  2.     {  
  3.         private static Mutex _mutex = null;  
  4.   
  5.         protected override void OnStartup(StartupEventArgs e)  
  6.         {  
  7.             const string appName = "MyAppName";  
  8.             bool createdNew;  
  9.   
  10.             _mutex = new Mutex(true, appName, out createdNew);  
  11.   
  12.             if (!createdNew)  
  13.             {  
  14.                 //app is already running! Exiting the application  
  15.                 Application.Current.Shutdown();  
  16.             }  
  17.   
  18.             base.OnStartup(e);  
  19.         }          
  20.     }  

I hope you enjoyed this brief Mutex usage introduction. Comments are more than welcome.