Search code examples
c#.net

Prevent multiple instances of a given app in .NET?


In .NET, how can I prevent multiple instances of an app from running at the same time and what caveats should I consider if there are multiple ways to do it?


Solution

  • Use Mutex. One of the examples above using GetProcessByName has many caveats. Here is a good article on the subject:

    https://web.archive.org/web/20230610150623/https://odetocode.com/blogs/scott/archive/2004/08/20/the-misunderstood-mutex.aspx

    [STAThread]
    static void Main() 
    {
       using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))
       {
          if(!mutex.WaitOne(0, false))
          {
             MessageBox.Show("Instance already running");
             return;
          }
       
          Application.Run(new Form1());
       }
    }
    
    private static string appGuid = "c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9";