I'm trying to ping a proxy, and time how long the response takes to get the ping before proceeding with my code, however my stopwatch is far too fast. Where am I going wrong here?
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;
}
}
The problem is that TimeSpan.Milliseconds
is actually the number of milliseconds since the last fully elapsed second, NOT the total number of elapsed milliseconds. i.e. If something runs for 1500 milliseconds, then the Milliseconds
property will return 500, NOT 1500. You need to use stopWatch.Elapsed.TotalMilliseconds
instead, which incidentally is a double
, not an int
.