0

我用它从控制器的动作中运行一个进程

            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
            }

process.WaitForExit(); 如果我出于某种原因不使用这里注册的代表process.Exited += new EventHandler(process_Exited);永远不会触发。

我在这里做错了什么?

4

1 回答 1

2

处理程序process_Exited永远不会触发,因为process变量和控制器在进程结束之前被垃圾收集。如果您取消注释process.WaitForExit(),则当前线程将被阻塞,直到进程结束,您的控制器和process变量将不会被识别为垃圾并且不会被收集。

于 2013-08-20T14:14:49.137 回答