HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Multithreaded host pinging application

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
hostpingingmultithreadedapplication

Problem

I'm working on a network monitoring application, that pings an unknown number of hosts. I've made a class PingHost with a function zping and I called it with the help of a timer once every 2 seconds to let the 2 pings to finish, even if one of them gets TimedOut. But I think a better solution is to generate a new thread for every ping, so that the ping of every host would be independent.

Can anyone give me a hint how to do this?

namespace pinguin
{
    public partial class Form1 : Form
    {
        public Form1()
        { 
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            PingHost caca = new PingHost();
            PingHost caca1 = new PingHost();
            this.label1.Text = caca.zping("89.115.14.160");
            this.label2.Text = caca1.zping("89.115.14.129");
        }

    }


public class PingHost
    {
        public string zping(string dest)
        {
            Application.DoEvents();
            Ping sender = new Ping();
            PingOptions options = new PingOptions();
            options.DontFragment = true;

            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 50;
            int failed = 0;
            int pingAmount = 5;
            string stat = "";
            PingReply reply = sender.Send(dest, timeout, buffer, options);
            if (reply.Status == IPStatus.Success)
            {
                stat = "ok";
            }
            else
            {
                stat = "not ok!";
            }
            return stat;
        }
    }
}

Solution

You can use SendAsync:

sender.PingCompleted += new PingCompletedEventHandler (PingCompletedCallback);
sender.SendAsync(dest, timeout, buffer, options, textLabel);


And the callback:

private static void PingCompletedCallback (object label, PingCompletedEventArgs e)
{
   if (e.Reply.Status == IPStatus.Success)
   {
      label.Text = "ok";
   }
   else
   {
      label.Text = "not ok!";
   }
}


Disclaimer: I haven't run this code. I believe the delegate will be able to access the label, but I've had issues with it in the past.

Code Snippets

sender.PingCompleted += new PingCompletedEventHandler (PingCompletedCallback);
sender.SendAsync(dest, timeout, buffer, options, textLabel);
private static void PingCompletedCallback (object label, PingCompletedEventArgs e)
{
   if (e.Reply.Status == IPStatus.Success)
   {
      label.Text = "ok";
   }
   else
   {
      label.Text = "not ok!";
   }
}

Context

StackExchange Code Review Q#1202, answer score: 6

Revisions (0)

No revisions yet.