Question

This code is supposed to not allow multiple running instances of an application but does not work. What is wrong?

public Main()
{
    InitializeComponent();

    // Dont allow multiple instances
    bool isNew = false;
    Mutex mutex = new Mutex(true, "Application", out isNew);
    if (!isNew)
    {
        RadMessageBox.Show(this, "Application is already running.", "Error", 
                 MessageBoxButtons.OK, RadMessageIcon.Error);

        Environment.Exit(0);
    }
}
Was it helpful?

Solution

Your Mutex is going out of scope. That means when the second instance of your app runs, the first instance no longer has a mutex. So the second instance doesn't "see" the first. I would recommend putting this code in your Program class, rather than in a form.

static class Program
{
    static void Main()
    {
        bool isNew = false;
        using (var mutex = new Mutex(false, "MyApplicationName", out isNew))
        {
            if (isNew)
                Run();
            else
                RadMessageBox.Show(this, "Application is already running.", "Error", MessageBoxButtons.OK, RadMessageIcon.Error);
        }
    }

    static void Run()
    {
        // the rest of your program goes here
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top