我有一个文本框和一个按钮.该按钮调用Ping(),我希望显示ping的任何进度textBox1.
void Ping()
{
p = new Process();
p.StartInfo.FileName = "ping";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.Arguments = "www.microsoft.com";
p.Start();
textBox1.Text = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
Run Code Online (Sandbox Code Playgroud)
怎么实现呢?我上面写的当前实现并未显示进度,而是显示最终输出.
async void Test()
{
await Ping("www.google.com");
}
Task Ping(string host)
{
var tcs = new TaskCompletionSource<object>();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "ping.exe";
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.Arguments = host;
var proc = Process.Start(psi);
proc.OutputDataReceived += (s, e) => {
Action action = () => textBox1.Text += e.Data + Environment.NewLine;
this.Invoke(action);
};
proc.Exited += (s, e) => tcs.SetResult(null);
proc.EnableRaisingEvents = true;
proc.BeginOutputReadLine();
return tcs.Task;
}
Run Code Online (Sandbox Code Playgroud)
结果
Pinging www.google.com [64.15.117.154] with 32 bytes of data:
Reply from 64.15.117.154: bytes=32 time=50ms TTL=55
Reply from 64.15.117.154: bytes=32 time=45ms TTL=55
Reply from 64.15.117.154: bytes=32 time=45ms TTL=55
Reply from 64.15.117.154: bytes=32 time=46ms TTL=55
Ping statistics for 64.15.117.154:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 45ms, Maximum = 50ms, Average = 46ms
Run Code Online (Sandbox Code Playgroud)
话虽如此,我会使用Ping该类而不是启动外部应用程序
var ping = new System.Net.NetworkInformation.Ping();
var pingReply = await ping.SendPingAsync("www.google.com");
Console.WriteLine("{0} {1} {2}",pingReply.Address,
pingReply.RoundtripTime,
pingReply.Status);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1210 次 |
| 最近记录: |