C# UI在读取端口时挂起
我正在使用以下代码从以太网端口读取数据:C# UI在读取端口时挂起,c#,sockets,C#,Sockets,我正在使用以下代码从以太网端口读取数据: System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient(); class ClsReadPort { public void Connect() { try { clientSocket = new System.Net.Sockets.Tcp
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
class ClsReadPort
{
public void Connect()
{
try
{
clientSocket = new System.Net.Sockets.TcpClient();
if (!clientSocket.Connected)
{
clientSocket.Connect("192.168.0.25", 1324);
}
}
catch (Exception ex)
{
MsgBox(ex.Message)
}
}
public string Capture()
{
try
{
if (clientSocket.Connected)
{
NetworkStream serverStream = clientSocket.GetStream();
byte[] inStream = new byte[clientSocket.ReceiveBufferSize + 1];
serverStream.Read(inStream, 0, Convert.ToInt32(clientSocket.ReceiveBufferSize));
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
oCapture = returndata;
}
}
}
catch (Exception ex)
{
MsgBox(ex.Message)
}
}
}
在更新读取值的主程序中:
ClsReadPort objRead = new ClsReadPort();
private void timer1_Tick(object sender, EventArgs e)
{
txtReadValue.Value = objRead.Capture();
}
它工作得很好。但一旦以太网电缆断开,整个用户界面就会被挂起。它保持在这条线上:
serverStream.Read(inStream, 0, Convert.ToInt32(clientSocket.ReceiveBufferSize));
在.NET4.5中,如何在不影响UI的情况下将其作为并行任务执行???您可以使用并等待它们 对于异步,请看一看
这里还有一个无等待表单MSDN,您可以使用Dispatcher在单独的线程中启动捕获任务
Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
try
{
txtReadValue.Value = objRead.Capture();
}
catch { }
}
我用1秒的时间运行它。“没事吧?”奥利瓦沙姆嗯,不,不是。您有一个clientSocket成员,共享该成员时可能会遇到线程问题,可能会有几个线程正在运行,这会修改您的txtReadValue.Value。您必须重写您的代码,以使用带有某些var的监视器锁定或检查您的操作状态,以防止在上一个线程未完成之前创建新线程。