Showing posts with label Mutex. Show all posts
Showing posts with label Mutex. Show all posts

Saturday, June 16, 2018

How to make sure only single instance of your application is running?


There are many ways to keep running single instance of your application. In this article i'll explain how you can use Mutex and GetProcesses to keep single instance of your application.


Mutex  



Mutex is threading synchronisation mechanism. Named mutex works across multiple applications. I've explained more about Mutex in my previous article under Threading. Below example demonstrated how mutex is used to keep single instance of your console application.

Code –
class Program
{
    static void Main(string[] args)
    {
        bool isFirstInstance;
        using (Mutex mutex = new Mutex(true, "MyApp", out isFirstInstance))
        {
            if (isFirstInstance)
            {
                Console.WriteLine("Welcome, Running first instance of MyApp");
                Console.Read();
            }
            else
            {
                Console.WriteLine("One instance of MyApp is already running.");
                Console.Read();
            }
        }
    }
}

Output –



Similar code you can do for WPF application.

Code –
public partial class App : Application
{
    private static Mutex mutex = null;
    protected override void OnStartup(StartupEventArgs e)
    {
        bool isFirstInstance;
        mutex = new Mutex(true, "MyWPFApp", out isFirstInstance);
        if (isFirstInstance)
        {
            MessageBox.Show("Welcome, Running first instance of MyWPFApp", "Info");
            MainWindow window = new MainWindow();
            window.Show();
        }
        else
        {
            MessageBox.Show("One instance of MyWPFApp is already running.", "Info");
            Application.Current.Shutdown();
        }
           

        base.OnStartup(e);
    }
}

Output –



GetProcesses  


One more way to check single instance of your running application using Get Processes. See below example.

static void Main(string[] args)
{
    //get process count of your application
    if (System.Diagnostics.Process.GetProcessesByName(
        System.IO.Path.GetFileNameWithoutExtension(
            System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1)
    {
        Console.WriteLine("One instance is already running so closing this instance");
        Console.Read();
        System.Diagnostics.Process.GetCurrentProcess().Kill();
    }
    else
    {
        Console.WriteLine("Welcome, Running first instance.");
        Console.Read();
    }

}





You can download code from Gist.

Thank you for reading this article. Please leave your feedback in comments below.

Reference –

See also –

Monday, December 5, 2011

Semaphore - Threading



Semaphore is similar to Lock and Mutex statements except it limits the number of concurrent thread can access the resource at a time. Using semaphore we can control how many thread can access resource at a time. The lock can be acquired using WaitOne method of Semaphore and can also be released using Release method of Semaphore. 


If Semaphore is named, it can be accessible throughout processes similar to Mutex. There is no guaranteed order in which blocked thread enters semaphore. Checkout Semaphore page on MSDN for more information.

In following example, five threads try to enter semaphore but at a time only three threads can enter.

public class MyClass
{
public static Semaphore semaphore = new Semaphore(3,3);
public static void DoWork(object i)
{
    Console.WriteLine("Thread {0} wants to enter", i.ToString());

    semaphore.WaitOne();

    Console.WriteLine("Thread {0} enters", i.ToString());

    Thread.Sleep(2000 * (int)i);

    Console.WriteLine("Thread {0} is leaving", i.ToString());

    semaphore.Release();
}
public static void Main()
{
    semaphore = new Semaphore(3, 3);
    for (int i = 1; i <= 5; i++)
    {
        Thread t1 = new Thread(new ParameterizedThreadStart(DoWork));
        t1.Start(i);
    }
}
}


As per above example, Semaphore instant created inside main method with limiting 3 threads. The loop creates five threads and tries to enter semaphore but semaphore only allows three threads at a time.


With Dotnet Framework 4.0, SemaphoreSlim class was introduced. This class is Optimized and faster than Semaphore. SemaphoreSlim was introduced specially for faster lock/release and for parallel programming.



Mutex - Threading



Mutex ensures only one thread can enter particular section. Mutex is similar to lock statement the only difference is that Mutex can work across multiple processes while lock can work only for multiple threads. Mutex ensures only one process (application) can run at a time. Mutex is slower than lock. We can use WaitOne method to acquire lock and ReleaseMutex to release lock.

There are two types of mutex available, named and unnamed. Unnamed mutex are called as local mutex and available within your process. Only threads inside your process can access it. While named mutex are visible throughout the operating system and multiple processes can be able to access it. Checkout Mutex page on MSDN for more information.    

Let’s understand with simple example.

public static Mutex mutex = new Mutex();
public static void DoWork()
{
        mutex.WaitOne();

        Console.WriteLine("Thread {0} has entered", Thread.CurrentThread.Name);

        Thread.Sleep(2000);

        Console.WriteLine("Thread {0} is leaving", Thread.CurrentThread.Name);

        mutex.ReleaseMutex();
}
public static void Main()
{
       for (int i = 0; i < 3; i++)
        {
            Thread t1 = new Thread(new ThreadStart(DoWork));
            t1.Name = "Thread " + i.ToString();
            t1.Start();
        }
}     


As demonstrated in above code, WaitOne method requests to acquire a lock and ReleaseMutex method request to release lock. Mutex can only be released by the thread that acquired it. The main method creates three threads one by one and tries to access DoWork method. DoWork method implements mutex so only one thread at a time will able to access.