Why is my process's Exited method not being called?

C#.Net

C# Problem Overview


I have following code, but why is the ProcessExited method never called? It is the same if I don't a 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
}

C# Solutions


Solution 1 - C#

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); 

Solution 2 - C#

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?

Solution 3 - C#

You must set Process.EnableRaisingEvents to true.

Solution 4 - C#

I've come across examples that place new Process() in a using clause. Do not do that if you want to use the Exited feature. The using clause destroys the instance along with any event handles on Exited.

This...

using(var process = new Process())
{
   // your logic here
}

Should be this...

var process = new Process();

Solution 5 - C#

Set correctionProcess.EnableRaisingEvents = true

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question5YrsLaterDBAView Question on Stackoverflow
Solution 1 - C#ElishaView Answer on Stackoverflow
Solution 2 - C#CodingGorillaView Answer on Stackoverflow
Solution 3 - C#Sam BView Answer on Stackoverflow
Solution 4 - C#Adam CoxView Answer on Stackoverflow
Solution 5 - C#Gary L Cox JrView Answer on Stackoverflow