我正在使用以下代码从以太网端口读取数据:
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();
}
它工作正常。但是,一旦以太网电缆断开连接,整个 UI 就会挂起。它停留在这条线上:
serverStream.Read(inStream, 0, Convert.ToInt32(clientSocket.ReceiveBufferSize));
如何在不影响 UI 的情况下将其作为并行任务执行?