C#/.NET: Process.HasExited returns true even though process is running??
Posted
by johnrl
on Stack Overflow
See other posts from Stack Overflow
or by johnrl
Published on 2010-03-25T21:52:20Z
Indexed on
2010/03/25
22:03 UTC
Read the original article
Hit count: 708
I have been observing that Process.HasExited sometimes returns true even though the process is still running.
My code below starts a process with name "testprogram.exe" and then waits for it to exit. The problem is that sometimes I get thrown the exception; it seems that even though HasExited returns TRUE the process itself is still alive in the system - how can this be??
My program writes to a logfile just before it terminates and thus I need to be absolutely sure that this logfile exists (aka the process has terminated/finished) before reading it. Continuously checking for it's existence is not an option.
// Create new process object
process = new Process();
// Setup event handlers
process.EnableRaisingEvents = true;
process.OutputDataReceived += OutputDataReceivedEvent;
process.ErrorDataReceived += ErrorDataReceivedEvent;
process.Exited += ProgramExitedEvent;
// Setup start info
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = ExePath,
UseShellExecute = false, // Must be false to redirect IO
RedirectStandardOutput = true,
RedirectStandardError = true,
Arguments = arguments
};
process.StartInfo = psi;
// Start the program
process.Start();
while (!process.HasExited)
Thread.Sleep( 500 );
Process[] p = Process.GetProcessesByName( "testprogram" );
if ( p.Length != 0 )
throw new Exception("Oh oh");
© Stack Overflow or respective owner