c#ProcessStartInfo.Start-读取输出但超时如果你想启动另一个进程并等待(超时)完成,你可以使用以下(来自MSDN)。//设置一个超时值。int超时=5000;//获取系统文件夹的路径。字符串sysFolder=Environment.GetFolderPath(Environment.SpecialFolder.System);//创建一个新的进程信息结构。ProcessStartInfopInfo=newProcessStartInfo();//设置要打开的文件名。pInfo.FileName=sysFolder+@"eula.txt";//启动进程。进程p=Process.Start(pInfo);//等待窗口完成加载。p.WaitForInputIdle();//等待进程退出或超时。p.WaitForExit(超时);//检查进程是否还在运行。if(p.HasExited==false)//进程还在运行。//测试进程是否挂掉。if(p.Responding)//进程正在响应;关闭主窗口。p.CloseMainWindow();else//进程没有响应;强制进程关闭。p.Kill();MessageBox.Show("代码继续...");如果要启动另一个进程并读取其输出,则可以使用以下模式(来自SO)//启动子进程。Processp=newProcess();//重定向ch的输出流旧过程。p.StartInfo.UseShellExecute=false;p.StartInfo.RedirectStandardOutput=true;p.StartInfo.FileName="Write500Lines.exe";p.开始();//在读取到其重定向流的末尾之前,不要等待子进程退出。//p.WaitForExit();//先读取输出流,然后等待。字符串输出=p.StandardOutput.ReadToEnd();p.WaitForExit();如果运行过程出现问题,结合读取所有输入而不是死锁和超时?如果输出缓冲区填充了超过4KB的数据,此技术将挂起。一种更简单的方法是注册一个代理,以便在将某些内容写入输出流时得到通知。我之前在另一篇文章中建议过这种方法:ProcessStartInfoprocessInfo=newProcessStartInfo("Write500Lines.exe");processInfo.ErrorDialog=false;processInfo.UseShellExecute=false;processInfo.RedirectStandardOutput=true;processInfo.RedirectStandardError=;Processproc=Process.Start(processInfo);//您可以将任何与适当//签名匹配的委托传递给ErrorDataReceived和OutputDataReceivedproc.ErrorDataReceived+=(sender,errorLine)=>{if(errorLine.Data!=null)Trace.WriteLine(errorLine.Data);};proc.OutputDataReceived+=(sender,outputLine)=>{if(outputLine.Data!=null)Trace.WriteLine(outputLine.Data);};proc.BeginErrorReadLine();proc.BeginOutputReadLine();proc.WaitForExit();您不必将两者结合起来——当输出被发送到StandardOutput时,Process类会触发一个事件——OutputDataReceived。如果您订阅该事件,您将能够在它到达时读取输出,并且在主程序循环中您仍然可以超时。您可以尝试将第一种方法修改为类似Processp=Process.Start(pInfo);字符串输出=string.Empty;线程t=newThread(()=>output=p.StandardOutput.ReadToEnd());t.开始();//等待窗口完成加载。p.WaitForInputIdle();//等待进程退出或超时。p.WaitForExit(超时);voidOpenWithStartInfo(){ProcessStartInfostartInfo=newProcessStartInfo("IExplore.exe","Default2.aspx");startInfo.WindowStyle=ProcessWindowStyle.Minimized;进程p=Process.Start(startInfo);p.WaitForInputIdle();//p.WaitForExit(2);p.杀();您也可以像这样使用APM:为ReadToEnd调用定义一个委托:privatedelegatestringReadToEndDelegate();然后使用委托调用方法,如下所示:ReadToEndDelegateasyncCall=reader.ReadToEnd;IAsyncResultasyncResult=asyncCall.BeginInvoke(null,null);asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(10));asyncCall.EndInvoke(asyncResult);编辑:为清楚起见,删除了错误处理。只需将第一个示例中WaitForExit()调用下方的所有内容添加到第二个示例。以上是C#学习教程:c#ProcessStartInfo.Start-读取输出但超时,分享所有内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注。本文来自网络收集,不代表作品如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处:
