C#如何等待代理ping?
C# how to wait for a proxy ping?
我正在尝试对代理执行 ping 操作,并计算在继续执行我的代码之前响应获得 ping 所需的时间,但是我的秒表太快了。我哪里错了?
private async void idunno()
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var x = await CanPing2();
Console.WriteLine("is proxy alvie: " + x);
stopWatch.Stop();
int ts = stopWatch.Elapsed.Milliseconds;
Console.WriteLine("RunTime " + ts);
Console.WriteLine("RunTime " + ts2);
}
public async Task<bool> CanPing2()
{
string ip = "170.130.59.107";
Console.WriteLine(ip);
Ping ping = new Ping();
try
{
PingReply reply = await ping.SendPingAsync(ip, 6000);
if (reply == null) return false;
Console.WriteLine("cp2 is alive: " + IPStatus.Success);
return (reply.Status == IPStatus.Success);
}
catch (PingException e)
{
Console.WriteLine("cp2: ex: " + IPStatus.Success);
return false;
}
}
问题是 TimeSpan.Milliseconds
实际上是自上次完全流逝的秒数以来的毫秒数,而不是流逝的总毫秒数。即,如果某些东西运行了 1500 毫秒,那么 Milliseconds
属性 将 return 500,而不是 1500。您需要使用 stopWatch.Elapsed.TotalMilliseconds
来代替,顺便说一下,它是一个 double
, 而不是 int
.
我正在尝试对代理执行 ping 操作,并计算在继续执行我的代码之前响应获得 ping 所需的时间,但是我的秒表太快了。我哪里错了?
private async void idunno()
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var x = await CanPing2();
Console.WriteLine("is proxy alvie: " + x);
stopWatch.Stop();
int ts = stopWatch.Elapsed.Milliseconds;
Console.WriteLine("RunTime " + ts);
Console.WriteLine("RunTime " + ts2);
}
public async Task<bool> CanPing2()
{
string ip = "170.130.59.107";
Console.WriteLine(ip);
Ping ping = new Ping();
try
{
PingReply reply = await ping.SendPingAsync(ip, 6000);
if (reply == null) return false;
Console.WriteLine("cp2 is alive: " + IPStatus.Success);
return (reply.Status == IPStatus.Success);
}
catch (PingException e)
{
Console.WriteLine("cp2: ex: " + IPStatus.Success);
return false;
}
}
问题是 TimeSpan.Milliseconds
实际上是自上次完全流逝的秒数以来的毫秒数,而不是流逝的总毫秒数。即,如果某些东西运行了 1500 毫秒,那么 Milliseconds
属性 将 return 500,而不是 1500。您需要使用 stopWatch.Elapsed.TotalMilliseconds
来代替,顺便说一下,它是一个 double
, 而不是 int
.