Jameel Moideen
Jameel Moideen

Reputation: 7931

Mutex results are varying in systems

I have a console application in C# and I want to restrict my application to run only one instance at a time.It's work fine in one system.When i try to run the exe in another system it's not working.The problem is In one pc i can open only one exe. When i try to run on another pc i can open more than one exe.How can i resolve this issue? Below are the code i have written.

string mutexId = Application.ProductName;
using (var mutex = new Mutex(false, mutexId))
{
    if (!mutex.WaitOne(0, false))
    {
        MessageBox.Show("Instance Already Running!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        return;
    }

        //Remaining Code here
}

Upvotes: 0

Views: 114

Answers (2)

Andrey Voloshin
Andrey Voloshin

Reputation: 345

My good old solution:

    private static bool IsAlreadyRunning()
    {
        string strLoc = Assembly.GetExecutingAssembly().Location;
        FileSystemInfo fileInfo = new FileInfo(strLoc);
        string sExeName = fileInfo.Name;
        bool bCreatedNew;

        Mutex mutex = new Mutex(true, "Global\\"+sExeName, out bCreatedNew);
        if (bCreatedNew)
            mutex.ReleaseMutex();

        return !bCreatedNew;
    }

Source

Upvotes: 0

Matthew Watson
Matthew Watson

Reputation: 109557

I would use this approach instead anyway:

// Use a named EventWaitHandle to determine if the application is already running.

bool eventWasCreatedByThisInstance;

using (new EventWaitHandle(false, EventResetMode.ManualReset, Application.ProductName, out eventWasCreatedByThisInstance))
{
    if (eventWasCreatedByThisInstance)
    {
        runTheProgram();
        return;
    }
    else // This instance didn't create the event, therefore another instance must be running.
    {
        return; // Display warning message here if you need it.
    }
}

Upvotes: 1

Related Questions