我知道有很多關於凍結的foreach形式的東西,但我不能找到一個解決我的問題。我已經有這個程序的服務器部分的工作,我試圖讓一個客戶端,雖然連接到服務器這一代碼將預製txtConn.AppendText("Attempting connection.");
的foreach冷凍形式
這是我對套接字連接
private static Socket ConnectSocket(string server, int port, RichTextBox txtConn, BackgroundWorker backgroundWorker1)
{
Socket s = null;
IPHostEntry hostEntry = null;
// Get host related information.
hostEntry = Dns.GetHostEntry(server);
// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
backgroundWorker1.RunWorkerAsync();
foreach (IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine(ipe);
try
{
attempt++;
txtConn.Select(txtConn.TextLength, 0);
txtConn.SelectionColor = Color.Aqua;
if (attempt == 1)
{
txtConn.AppendText("Attempting connection.");
}
else if (attempt > 1)
{
txtConn.AppendText("\r" + "Attempting connection.");
}
txtConn.SelectionColor = txtConn.ForeColor;
tempSocket.Connect(ipe);
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
txtConn.Select(txtConn.TextLength, 0);
txtConn.SelectionColor = Color.Red;
txtConn.AppendText("\r\n" + "Connection could not be established.");
txtConn.SelectionColor = txtConn.ForeColor;
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
txtConn.Select(txtConn.TextLength, 0);
txtConn.SelectionColor = Color.Red;
txtConn.AppendText("\r\n" + "Connection could not be established.");
txtConn.SelectionColor = txtConn.ForeColor;
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
txtConn.Select(txtConn.TextLength, 0);
txtConn.SelectionColor = Color.Red;
txtConn.AppendText("\r\n" + "Connection could not be established.");
txtConn.SelectionColor = txtConn.ForeColor;
}
if (tempSocket.Connected)
{
Console.WriteLine("Connected");
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}
代碼
當我運行該程序,並與連說了錯誤的端口,它會檢查我的電腦上所有可能的IPS和等待,直到後foreach語句,以顯示錯誤或任何東西。我怎樣才能讓它積極展示這一點? This is when it runs
* foreach凍結表單*?你在說這個程序變得沒有反應嗎?聽起來你需要閱讀'Thread's。 –
我看到你已經有了一個後臺工作者。它執行什麼代碼?爲什麼不把for循環放在後臺工作DoWork事件處理程序中? –