How to prevent duplicate application instances






Sometimes it’s important to make sure your program isn’t running more than one instance at the time. In C# this is an easy task using the provided .NET libraries.

In this short illustrative example the program counts the number of processes with the same assembly name as this current assembly. If any are found, the program refuses to start and instead kills the current thread.

using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
namespace DuplicateTesting
{
    class Program
    {
        static void Main(string[] args)
        {
            if (Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)).Length > 1)
            { 
                Console.WriteLine("An instance of this program is already running");
                Console.ReadKey();
                Process.GetCurrentProcess().Kill();
            }
            Console.WriteLine("Welcome!");
            Console.ReadKey();
        }
    }
}






In the screen shot below you can see the result of running the program twice. The result is just as expected.
Preventing duplicate instances