I was trying to ping a server using the Ping class, but after like 10 times that the method returns true, I keep getting false(which means the server is down[?] and it isn’t) Here’s the method:
public bool IsConnectedToInternet()
{
Ping p = new Ping();
try
{
PingReply reply = p.Send("www.uic.co.il", 1000);
if (reply.Status == IPStatus.Success)
return true;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
return false;
}
private void start_Click(object sender, EventArgs e)
{
for (; ; )
{
Console.WriteLine(IsConnectedToInternet);
}
}
Why am I keep getting false after a while?
Thank you.
You’re flooding the server with requests:
will loop as fast as possible sending request after request.
If you are just coding a keep alive service or service status control then using a timer that pings every minute or even every 10 minutes should be good enough.
Additionally, as others have pointed out in their comments, you are abusing properties by doing the ping in the getter as the call can potentially take some time and property getters should really return, if not instantly then very quickly. A
CheckConnection()method would have clearer intent.