0

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.

Drew Gaynor
  • 8,292
  • 5
  • 40
  • 53
BolnoYGaD
  • 31
  • 2
  • 9
  • Check out [BackgroundWorker](http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx). – Vlad Nov 14 '14 at 16:10
  • I guess my brain frozen as well bw looks like the simpliest way to do what i want but i just dont understand how should i implement it. Examples with my code would be realy helpfull. thank you any way :) – BolnoYGaD Nov 14 '14 at 16:46
  • ok i was able to fit BW into my code. Tho i've used example from Amandeep Saini answer =) – BolnoYGaD Nov 14 '14 at 18:00

1 Answers1

0

You should call your PCIsOnline(textBox.Text) function in a separate thread. Maybe this could help : how to call the method in thread with aruguments and return some value Best of luck!

Community
  • 1
  • 1