I use this to run a process from a controller's action
var psi = new ProcessStartInfo(utilityPath, String.Format("{0} {1}", inputfilePath, outputfilePath))
{
WorkingDirectory = Environment.CurrentDirectory,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
using (var process = new Process { StartInfo = psi })
{
process.EnableRaisingEvents = true;
process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
process.ErrorDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
process.Exited += new EventHandler(process_Exited);
// start the process and start reading the standard and error outputs
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
//process.WaitForExit(); //If this is commented out the delegate process_Exited never fires
}
if i don't use process.WaitForExit();
for some reason the delegate registered here process.Exited += new EventHandler(process_Exited);
never fires.
What am i doing wrong here ?
Handler process_Exited
never fires because process
variable and controller are garbage collected before the process ends. If you uncomment process.WaitForExit()
then current thread will be blocked until the process ends and your controller and process
variable will not be recognised as garbage and will not be collected.