Search code examples
c#.netmstsc

How to wait until MSTSC.exe exits


I have created a management application that also allows to quickly access a remote desktop session to remote machines. I need to wait until the process ends, so I can close the VPN connection to the remote server. Everything works fine, except waiting for the process to end.

The following code is being used to start the MSTSC process and wait until it ends:

var process = new Process
{
  StartInfo = new ProcessStartInfo("mstsc.exe"),
  EnableRaisingEvents = true
};
process.Exited += (o, e) => Console.WriteLine("Process stopped.");
process.Start();
Console.ReadLine();

The Exited event is raised almost immediately after the program starts. When I replace mstsc.exe with notepad.exe everything works as expected. I thought that MSTSC might fork itself and abort the initial process.

But it is possible to wait for MSTSC to end using the following command (from the commandline):

start /wait mstsc.exe

This command doesn't return until I exit the remote desktop session. Given that information I replaced my code with this:

var process = new Process
{
  StartInfo = new ProcessStartInfo("cmd.exe"),
  Arguments = "/c start /wait mstsc.exe",
  EnableRaisingEvents = true
};
process.Exited += (o, e) => Console.WriteLine("Process stopped.");
process.Start();
Console.ReadLine();

This would run CMD.exe and it will issue the start /wait mstsc.exe command. If that ends, the CMD process ends as well and I'm fine (with a nasty workaround, but okay). Unfortunately, this doesn't happen. The CMD process terminates immediately. Somebody knows what I am doing wrong?


Solution

  • process.WaitForExit();
    

    Won't work before Windows 11 because mstsc on start opens new copy of itself and closes original.

    process.WaitForExit();    
    process = Process.GetProcessesByName(process.ProcessName).First();
    process.WaitForExit();
    

    Will work but it's awful workaround.

    Update 1:

    It seems that mstsc closes original process but NOT it's output stream! So you can wait for process StandardOutput to close.

    var process = new Process
    {
        StartInfo = new ProcessStartInfo("mstsc.exe") { UseShellExecute = false, RedirectStandardOutput = true }
    };
    process.Start();
    process.StandardOutput.ReadToEnd(); //This will wait for stream to close.
    

    Or if you don't want to block current thread:

    var process = new Process
    {
        StartInfo = new ProcessStartInfo("mstsc.exe") { UseShellExecute = false, RedirectStandardOutput = true }
    };
    
    process.Start();
    
    var outputResultPromise = process.StandardOutput.ReadToEndAsync();
    outputResultPromise.ContinueWith(o=> Console.WriteLine("Stream closed"));
    
    Console.ReadLine();