Singelton application with C#

By | November 14

A singelton application is an application which only allows running one instance of itself per machine. e.g. Microsoft Outlook is a singelton application. Everytime the user starts the application it will check if an instance is already running. If its not running it will launch it otherwise it will focus to the current one. Here is the source of how to create a singelton application with C# and .net …

  1. using System.Threading;
  2.  
  3. //Allows to run the application only once per machine
  4. public static class SingeltonApplication {
  5.     static Mutex _mutex;
  6.     public static void Run(Form form) {
  7.         if (IsFirstInstance()) {
  8.             Application.ApplicationExit += OnExit;
  9.             Application.Run(mainForm);
  10.         }
  11.     }
  12.  
  13.     public bool IsFirstInstance() {
  14.         Assembly a = Assembly.GetEntyAssembly();
  15.         _mutex = new Mutex(false, a.FullName);
  16.         bool owned = false;
  17.         owned = _mutex.WaitOne(TimeSpan.Zero, false);
  18.         return owned;
  19.     }
  20.  
  21.     static void OnExit(object sender, EventArgs args) {
  22.         _mutex.ReleaseMutex();
  23.         _mutex.Close();
  24.     }
  25. }

The trick here is to get a cross-process communication because every application runs in its own process. This is achieved with a Mutex which is available system wide. We use the name of the application for the identification of the Mutex.

the source is inspired from the book “.net Components, Juval Löwy, O’Reilly United States” page 231

Category: c#