So I have a textbox where I type name of the PC that needs to be pinged. I run ping when focus is lost:
private void Name_LostFocus(object sender, System.EventArgs e)
{
if (PCIsOnline(textBox.Text))
{
textBox.Background = Brushes.LightGreen;
}
else
{
textBox.Background = Brushes.LightSalmon;
}
}
PCIsOnline looks like this:
public static bool PCIsOnline(string arg)
{
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 40;
try
{
PingReply reply = pingSender.Send(arg, timeout,
buffer, options);
if (reply.Status == IPStatus.Success)
return true;
else
return false;
}
catch
{
return false;
}
}
When PC is online, everything is fine and I get no freeze, but when PC is offline my app freezes for some time. It's normal I know, pinging offline PC takes time. But my question is this: how can I launch ping in the background and when it ends this will change background color of a textbox that initiated ping depending on the result of a ping.
I've read some topics about this, running ping async, but that wasn't helpful in my case at least I wasn't able to implement it in my code.