我ping 50个IP地址但是当我点击开始时程序会冻结。
如何在不冻结的情况下完成。
private void button1_Click(object sender, EventArgs e)
{
string IP = textBox1.Text;
string[] IPBlocks = IP.Split('.');
for (int x = 0; x < 50; x++)
{
System.Threading.Thread.Sleep(50);
int IPLastBlock = Int32.Parse(IPBlocks[3]) + (x+1);
IP = IPBlocks[0]+"."+ IPBlocks[1]+"."+ IPBlocks[2]+"."+ IPLastBlock;
bool pingStatus = PingHost(IP);
textBox2.Text += String.Format("{0} => {1} \r\n", IP, pingStatus);
}
}
答案 0 :(得分:3)
在按钮上单击启动一个separte线程,这不会挂起你的屏幕
private void button1_Click(object sender, EventArgs e)
{
Thread newThread= new Thread(PingIP);
newThread.Start();
}
private void PingIP()
{
string IP = textBox1.Text;
string[] IPBlocks = IP.Split('.');
for (int x = 0; x < 50; x++)
{
System.Threading.Thread.Sleep(50);
int IPLastBlock = Int32.Parse(IPBlocks[3]) + (x+1);
IP = IPBlocks[0]+"."+ IPBlocks[1]+"."+ IPBlocks[2]+"."+ IPLastBlock;
bool pingStatus = PingHost(IP);
textBox2.Text += String.Format("{0} => {1} \r\n", IP, pingStatus);
}
}
答案 1 :(得分:1)
使用ThreadPool.QueueUserWorkItem
ThreadPool.QueueUserWorkItem(delegate {
bool pingStatus = PingHost(IP);
textBox2.Text += String.Format("{0} => {1} \r\n", IP, pingStatus);
});