我正在开发一个网络监控应用程序,这个应用程序的主机数量不详。我制作了一个带有函数PingHost的类zping,我每2秒用一个计时器调用它,让它完成,即使其中一个得到了TimedOut。但我认为更好的解决方案是为每一个ping生成一个新线程,这样每个主机的ping就会独立。
有人能告诉我怎么做吗?
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;
}
}
}发布于 2011-03-08 18:32:47
您可以使用SendAsync:
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!";
}
}免责声明:我没有运行这段代码。我相信这位代表能够接触到这个标签,但我过去曾有过一些问题。
https://codereview.stackexchange.com/questions/1202
复制相似问题