C# 多线程 ping
我正在开发一个网络监控应用程序,它对(未知)数量的主机执行 ping 操作。到目前为止我有下面的代码。我创建了一个带有函数 zping
的类 PingHost
,并在计时器的帮助下每 2 秒调用一次它,以让 2 个 ping 完成,即使一个其中一些得到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;
}
}
}
I'm working on a network monitoring application, that pings a (not known) number of hosts. So far I have the code below. 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;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 .NET 4,则可以使用
Parallel.Invoke
。If you use .NET 4 you can use
Parallel.Invoke
.您可以处理
Ping.PingCompleted
事件:然后使用:
旁注:为您的类和例程选择更合适的名称。 PingHost 更适合作为例程名称
You could handle the
Ping.PingCompleted
event:then use:
side note: Choose more suitable names for your classes and routines. PingHost is more suitable as a routine name
有一次我写了这样一个解决方案(它不断地 ping 大约 300 台机器):
Once I wrote such a solution (it constantly pings about 300 machines):