user6793946 user6793946 - 1 month ago 9x
C# Question

C# how to wait for a proxy ping?

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();

var x = await CanPing2();
Console.WriteLine("is proxy alvie: " + x);

int ts = stopWatch.Elapsed.Milliseconds;

Console.WriteLine("RunTime " + ts);

Console.WriteLine("RunTime " + ts2);
public async Task<bool> CanPing2()

string ip = "";
Ping ping = new Ping();

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.