【发布时间】:2011-01-08 00:39:24
【问题描述】:
我有一个应用程序可以 ping 本地子网上的每个可能的 IP,以编译响应 IP 地址的列表。目前它一次 ping 所有 255 个。是否可以将此应用程序转换为使用多个线程来通过一次 ping 多个线程来提高速度?我是多线程概念的新手,我认为这将是一种很好的学习方式(当然,只要有可能)。
此外,您可以指导我的任何风格改进也会有所帮助。
提前感谢
这是 backgroundWorker1_DoWork 事件中的当前 ping 方法。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
count = 0;
for (int i = 1; i < 255; i++)
{
Ping ping = new Ping();
PingReply pingreply = ping.Send(IPAddress.Parse(locip[0] + "." + locip[1] + "." + locip[2] + "." + i));
count += 1;
if (pingreply.Status == IPStatus.Success)
{
status = "o";
repAddress = pingreply.Address.ToString(); ;
repRoundtrip = pingreply.RoundtripTime.ToString();
repTTL = pingreply.Options.Ttl.ToString();
repBuffer = pingreply.Buffer.Length.ToString();
string[] lineBuffer = { status, repAddress, repRoundtrip, repTTL, repBuffer };
ipList.Rows.Add(lineBuffer);
}
progressBar.Invoke(new MethodInvoker(UpdateProgressBarByOne));
progressStatus.Text = ("Pinging IP " + count + " of 254");
}
button1.Enabled = true;
progressBar.Invoke(new MethodInvoker(ResetProgressBar));
}
【问题讨论】:
标签: c# multithreading network-programming backgroundworker