Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent multiple instances of a given app in .NET?

Tags:

c#

.net

People also ask

How do I restrict an app to one instance?

If you want to limit the application to one instance per machine (i.e. not one per logged on user), then you will need your mutex name to start with the prefix Global\ . If you don't add this prefix, a different instance of the mutex will be created by the OS for each user.

How do I block multiple instances of a program in Windows 10?

In order to disable multiple instances of an app on Windows 10, you need to install a free app called SingleInstance. Go ahead and download, and run the app. The app, by default, has one app pre-configured and that's the Calculator app on Windows 10.


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

http://odetocode.com/Blogs/scott/archive/2004/08/20/401.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";

if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
{
  AppLog.Write("Application XXXX already running. Only one instance of this application is allowed", AppLog.LogMessageType.Warn);
  return;
}

Here is the code you need to ensure that only one instance is running. This is the method of using a named mutex.

public class Program
{
    static System.Threading.Mutex singleton = new Mutex(true, "My App Name");

    static void Main(string[] args)
    {
        if (!singleton.WaitOne(TimeSpan.Zero, true))
        {
            //there is already another instance running!
            Application.Exit();
        }
    }
}

Hanselman has a post on using the WinFormsApplicationBase class from the Microsoft.VisualBasic assembly to do this.


1 - Create a reference in program.cs ->

using System.Diagnostics;

2 - Put into void Main() as the first line of code ->

 if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length >1)
                return;

That's it.


It sounds like there are 3 fundamental techniques that have been suggested so far.

  1. Derive from the Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase class and set the IsSingleInstance property to true. (I believe a caveat here is that this won't work with WPF applications, will it?)
  2. Use a named mutex and check if it's already been created.
  3. Get a list of running processes and compare the names of the processes. (This has the caveat of requiring your process name to be unique relative to any other processes running on a given user's machine.)

Any caveats I've missed?