Prevent Multiple Instances of .NET App

Sometimes there are good reasons not to allow any copies of your app to be executing alongside one another. We only want a single instance of the app running on any given machine.

The links below connect to downloadable examples of implementing a mutex lock in .NET applications.

Download the Console app example.

Below is the complete code from Program.cs of a WinForms C# app that shows usage of a mutex to prevent multiple instances:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;

namespace ProofreadingTracker
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            string mutexName = "Local\\" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            using (Mutex mutex = new Mutex(false, mutexName))
            {
                if (!mutex.WaitOne(0, false))
                {
                    MessageBox.Show("There is an instance of this application already running!", "Proofreading Tracker");
                    return;
                }
                else
                {
                    GC.Collect();
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());

                }
            }
        }
    }
}

Author: kyrathasoft

The only programmer in Glens Fork, Ky.