Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Easily Create a Singleton Application in C#

2.42/5 (4 votes)
1 May 2020MIT1 min read 12.2K   92  
This tip demonstrates how to create an app that only allows one instance to run at a time
This tip presents a quick and concise way to ensure only one instance of an application can run at a time.

Introduction

Occasionally, it's desirable to create an application that only allows for one instance to run. This tip shows you one such method using a systemwide named mutex to check for another instance.

Conceptualizing this Mess

The idea here is very simple. We wrap the entry point method with a creation or opening of a named mutex which exists across the entire OS, and all applications. We check the creation method to see if a new mutex was indeed created and if not, we can know that another instance is already running and exit.

Coding this Mess

Accomplishing the above is very simple. Here is the demo code in its entirety.

C#
using System;
using System.Reflection;
using System.Threading;

namespace SingletonMutex
{
    class Program
    {
        static void Main()
        {
            var appName = Assembly.GetEntryAssembly().GetName().Name ;
            var notAlreadyRunning = true;
            using (var mutex = new Mutex(true, appName + "Singleton", out notAlreadyRunning))
            {
                if (notAlreadyRunning)
                {
                    // do work here:
                    Console.WriteLine("Running. Press any key to exit...");
                    Console.ReadKey();

                }
                else
                    Console.Error.WriteLine(appName + " is already running.");
            }
        }
    }
}

The code above will work in any console application, and can easily be adapted to a Windows Forms or WPF application.

We need to pass a string that's unique to the application to the Mutex constructor for it to be system wide. Here, simply concatenate the assembly's filename with "Singleton".

Inside the using block, we simply check if a new mutex was created or already exists, which is what the notAlreadyRunning variable indicates. If it's true, we do our work. If it's false, we simply exit. That's where you'd put your own application code.

You can test the application in Visual Studio by doing Ctrl+F5 twice to run two instances.

History

  • 1st May, 2020 - Initial submission

License

This article, along with any associated source code and files, is licensed under The MIT License