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

How to read from output in real time and stop at certain time if needed

所以,我有这个工作代码来显示来自 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<string> Lines = new List<string>(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.