30

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?

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Warpin
  • 6,971
  • 12
  • 51
  • 77

2 Answers2

43

Prefix the name of the mutex with "Global\".

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

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\".

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Paul Kearney - pk
  • 5,435
  • 26
  • 28
  • 1
    I tried this method, but encounter an unhandled exception when trying to debug,I run VS as administrator, ----------- An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll Additional information: Access to the path 'Global\MDProduction' is denied. – Mac Lee Apr 27 '20 at 01:29
15

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
  • 868,454
  • 176
  • 1,908
  • 1,964