我ping 50個IP地址,但當我點擊開始時程序凍結。形式凍結for循環
我該怎麼做,而不結冰。
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);
}
}
把平進程(循環)在單獨的線程,並取得進展直到線程處理完成。 –
您不能在事件處理程序中執行冗長的任務,這會阻塞UI線程並阻止UI更新。您需要創建一個新線程來完成您的處理。請參閱http://stackoverflow.com/questions/28194943/creating-and-starting-a-task-on-the-ui-thread和http://stackoverflow.com/questions/661561/how-to-update-the -gui-from-another-thread-in-c –