Espere hasta que finalice un proceso


Tengo una aplicación que hace

Process.Start()

Para iniciar otra aplicación 'ABC'. Quiero esperar hasta que la aplicación termine (proceso muere) y continuar mi ejecución. ¿Cómo puedo hacerlo?

Puede haber varias instancias de la aplicación 'ABC' ejecutándose al mismo tiempo.

Author: rory.ap, 2010-06-30

8 answers

Creo que solo quieres esto:

var process = Process.Start(...);
process.WaitForExit();

Ver la página MSDN para el método. También tiene una sobrecarga en la que puede especificar el tiempo de espera, por lo que no está esperando para siempre.

 336
Author: Noldorin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-30 09:19:48

Uso Process.WaitForExit? O suscribirse a la Process.Exited evento si no quieres bloquear? Si eso no hace lo que usted quiere, por favor dénos más información sobre sus requisitos.

 120
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-30 09:19:19

Hago lo siguiente en mi solicitud:

Process process = new Process();
process.StartInfo.FileName = executable;
process.StartInfo.Arguments = arguments;
process.StartInfo.ErrorDialog = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
process.Start();
process.WaitForExit(1000 * 60 * 5);    // Wait up to five minutes.

Hay algunas características adicionales que puede encontrar útiles...

 32
Author: AnthonyLambert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-13 17:30:22

Puede usar wait for exit o puede capturar la propiedad HasExited y actualizar su interfaz de usuario para mantener al usuario "informado" (administración de expectativas):

System.Diagnostics.Process process = System.Diagnostics.Process.Start("cmd.exe");
while (!process.HasExited)
{
    //update UI
}
//done
 15
Author: riffnl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-26 14:21:31

Proceso.WaitForExit debería ser justo lo que estás buscando, creo.

 5
Author: Hans Olsson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-30 09:20:37

Tuve un caso en el que Process.HasExited no cambió después de cerrar la ventana perteneciente al proceso. Así que Process.WaitForExit() tampoco funcionó. Tuve que monitorear Process.Responding que fue a false después de cerrar la ventana de esa manera:

while (!_process.HasExited && _process.Responding) {
  Thread.Sleep(100);
}
...

Tal vez esto ayude a alguien.

 5
Author: Buka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-17 09:46:29

Como dice Jon Skeet, usa el Process.Exited:

proc.StartInfo.FileName = exportPath + @"\" + fileExe;
proc.Exited += new EventHandler(myProcess_Exited);
proc.Start();
inProcess = true;

while (inProcess)
{
    proc.Refresh();
    System.Threading.Thread.Sleep(10);
    if (proc.HasExited)
    {
        inProcess = false;
    }
}

private void myProcess_Exited(object sender, System.EventArgs e)
{
    inProcess = false;
    Console.WriteLine("Exit time:    {0}\r\n" +
      "Exit code:    {1}\r\n", proc.ExitTime, proc.ExitCode);
}
 0
Author: David Lopes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-24 11:37:35

Prueba esto:

string command = "...";
var process = Process.Start(command);
process.WaitForExit();
 -5
Author: user3065161,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-13 17:36:51