异步进程退出而不是从控制器触发c#

时间:2013-08-20 12:17:31

标签: asp.net-mvc-3 asynchronous delegates system.diagnostics

我用它从控制器的动作

运行一个过程
            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);永远不会触发。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

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