How do you make sure that only one instance of your application is running?

Quite often you may face the scenario to restrict only one instance of your application is allowed to run. I see many users use the System.Diagnostics. Process .GetCurrentProcess().ProcessName method and System.Diagnostics. Process .GetProcesses() method to loop thro’ the processes and verify the current process name is exists in the collection or not.

There is another better way to achieve this. We can use Mutex object in System.Threading namespace for this purpose. Here you go for the sample code.


namespace My_Samples
{
    using System;
    using System.Threading;

    class Program
    {
        static Mutex mutex;
        static void Main(string[] args)
        {
            string appName = "My Application";
            bool createdNew;
            bool initiallyOwned = true;
            mutex = new Mutex(initiallyOwned, appName, out createdNew);
            if (!createdNew)
            {
                System.Environment.Exit(0);
            }
            Console.WriteLine("Application Is Running...");
            Console.ReadLine();
        }
    }
}

The overloaded Mutex class converter takes 3 parameters

initiallyOwned - true to give the calling thread initial ownership of the named system mutex
appName – Current application name
createdNew –This is an Boolean out parameter which indicates whether the mutex is already created or not.

Here I just provided a Console sample; you may use the same in Winform or WPF applications with minor tweaking.

No comments:

Post a Comment