Foreach冷冻形式
本文关键字:冷冻 Foreach | 更新日期: 2023-09-27 18:28:30
我知道foreach冻结表单有很多问题,但我找不到解决问题的方法。我已经让这个程序的服务器部分工作了,我正在尝试让客户端在连接到服务器时执行txtConn.AppendText("Attempting connection.");
这是我的插座连接的代码
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;
}
我的程序看起来像这个
当我运行程序并连接到错误的端口时,它会检查我计算机上所有可能的ip,并等待foreach语句之后显示错误或任何内容。如何使其主动显示此信息?这是当它运行时
您需要在不同的线程中运行代码,以便UI在执行时仍然可以更新。
最简单的方法是将连接循环添加到ThreadPool中的新任务中。
ThreadPool.QueueUserWorkItem(i => {
// Connection loop goes here.
});
如果您需要其他选项,您也可以使用Task、BackgroundWorker等。
我刚刚回答了一个类似的问题,但为了针对您的特定情况进行扩展,看起来您实际上并没有使用backgroundWorker1。foreach应该在backgroundWorker1.DoWork事件引用的方法中完成。您还需要为backgroundWorker1.ProgressChanged事件创建一个方法。您可以使用ReportProgress传递一个字符串,然后将该消息附加到您的文本框中:
在Worker_DoWork方法中的foreach循环中,您将报告进度,而不是直接更新RichTextBox:
worker.ReportProgress(0, "Connection could not be established.");
然后在Worker_ProgressChanged方法中,您将使用类似的东西来更新RichTextBox:
txtConn.AppendText(e.UserState.ToString());
Use应该使用Socket
类中的Async
方法,或者在另一个线程中运行这些东西。您也可以使用BackgroundWorker
来执行此操作。