Home » c# » why Process's Exited method not being called?

why Process's Exited method not being called?

Posted by: admin November 29, 2017 Leave a comment

Questions:

I have following code, but why the ProcessExited method is never called? It is the same if I don’t use Windows shell (startInfo.UseShellExecute = false).

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = path;
startInfo.Arguments = rawDataFileName;
startInfo.WorkingDirectory = Util.GetParentDirectory(path, 1);

try
{
     Process correctionProcess = Process.Start(startInfo);
     correctionProcess.Exited += new EventHandler(ProcessExited);                   

     correctionProcess.WaitForExit();

     status = true;
}

…..

internal void ProcessExited(object sender, System.EventArgs e)
{
      //print out here
}
Answers:

In order to receive a callback on Exited event, the EnableRaisingEvents must be set to true.

Process correctionProcess = Process.Start(startInfo);
correctionProcess.EnableRaisingEvents = true;
correctionProcess.Exited += new EventHandler(ProcessExited); 

Questions:
Answers:

From MSDN:

The Exited event indicates that the
associated process exited. This
occurrence means either that the
process terminated (aborted) or
successfully closed. This event can
occur only if the value of the
EnableRaisingEvents property is true.

Have you set that property to true?

Questions:
Answers:

You must set Process.EnableRaisingEvents to true.

Questions:
Answers:

Set correctionProcess.EnableRaisingEvents = true