tags:

views:

180

answers:

2

My app is forced to use a 3rd party module which will blue-screen Windows if two instances are started at the same time on the same machine. To work around the issue, my C# app has a mutex:

    static Mutex mutex = new Mutex(true, "{MyApp_b9d19f99-b83e-4755-9b11-d204dbd6d096}");  

And I check if it's present - and if so I show an error message and close the app:

    bool IsAnotherInstanceRunning()
    {
        if (mutex.WaitOne(TimeSpan.Zero, true))
            return (true);
        else
            return (false);
    }

The problem is if two users can log in and open the application at the same time, and IsAnotherInstanceRunning() will return false.

How do I get around this?

+6  A: 

Change the mutex name to begin with Global\.

Source

On a server that is running Terminal Services, a named system mutex can have two levels of visibility. If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes, and both are visible to all processes in the terminal server session. That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes.

SLaks
+3  A: 

Prefix the name of the mutex with "Global\". From http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx:

If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\".

Paul Kearney - pk