如何实时读取输出并在需要时在特定时间停止

所以,我有这个工作代码来显示来自System.Diagnostics.Process ping和统计信息

 Process P = new Process(); P.StartInfo.FileName = "ping"; P.StartInfo.Arguments = "-c 3 8.8.8.8"; // Take 3 samples to 8.8.8.8 P.StartInfo.UseShellExecute = false; P.StartInfo.RedirectStandardOutput = true; string readData = ""; if (P.Start()) readData = P.StandardOutput.ReadToEnd(); // This will also wait for the process to at least close its stdout Console.Write(readData.ToString()); // Doing this, you will see how the 

我以这种方式处理字符串:

 List Lines = new List(readData.Replace("\r\n", "\n").Split('\n')); while (Lines.Count > 0 && !Lines[0].StartsWith("---")) { Match M = Regex.Match(Lines[0], @"^[\d]+ bytes from ([^:]+): [^ ]+ ttl=([\d]+) time=([^ ]+) ms"); if (M != null && M.Success) { string IP = M.Groups[1].Value; string TTL = M.Groups[2].Value; string timeStr = M.Groups[3].Value; Console.WriteLine(String.Format("Ping to {0} took {2} ms with a ttl of {1}", IP, TTL, timeStr)); // Parsing the timeStr will work the same way as above } Lines.RemoveAt(0); } 

ReadToEnd(); 等到标准输出关闭然后处理字符串。

我的问题是如何实时处理每行的字符串行,以及如何在特定时间内停止该过程并最终获得统计信息。

System.IO.StreamReader有一个名为ReadLine的方法,你想要使用它:

 if (P.Start()){ DateTime endTime = DateTime.Now.AddSeconds(5); while(!P.HasExited){ readData = P.StandardOutput.ReadLine(); // This will wait for the next line to be output completely Match M = Regex.Match(Lines[0], @"^[\d]+ bytes from ([^:]+): [^ ]+ ttl=([\d]+) time=([^ ]+) ms"); if (M != null && M.Success) { string IP = M.Groups[1].Value; string TTL = M.Groups[2].Value; string timeStr = M.Groups[3].Value; Console.WriteLine(String.Format("Ping to {0} took {2} ms with a ttl of {1}", IP, TTL, timeStr)); } if (endTime > DateTime.Now) P.Kill(); } } 

我引入了一个名为endTime的变量,该变量在未来5秒内被初始化,当达到该时间时,进程被终止,导致循环终止,因为P.HasExited现在变为true