Search code examples
c#.netwpfrdpterminal-services

How to disable multiple instances of my application running over RDP (Terminal Services)?


I have a c#/WPF application that on some clients sites runs over RPD i.e. the application resides on the clients server and users access through terminal services sessions.

The problem I'm having is that I can't prevent multiple instances of the application opening accidently. When the application is running locally on a machine I can block out multiple instances using the following:

var processName = Process.GetCurrentProcess().ProcessName;   
                if (Process.GetProcesses().Count(p => p.ProcessName.Equals(processName)) > 1)
                {
                    this.Log.LogInfo(this.GetType(), "Process already running. Shutting down.");
                    Application.Current.Shutdown();
                    Process.GetCurrentProcess().Kill();
                }    

However, over RPP this won't work as there may be other instances of the application running on different RDP sessions.

Anybody know how I can disable a second application instance running in the same RDP session?




Solution

  • In the past I've accomplished this using a Mutex. When creating the mutex you would use the naming convention Global\\MutexName to handle terminal services scenarios.

    // declare in your program
    private static Mutex mutex = null;
    
    bool createdNew;  
    mutex = new Mutex(true, "Global\\MutexName", out createdNew); 
    
    if (!createdNew)
    {
        // Application is already running, so shutdown
        Application.Current.Shutdown();     
    }