UI在读取端口时会挂起

时间:2013-03-28 07:03:01

标签: c# sockets

我正在使用以下代码从以太网​​端口读取:

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的情况下将其作为并行任务?

2 个答案:

答案 0 :(得分:1)

在.net 4.5中,您可以使用async methods并等待它们 对于Async看看here

这里还有一个Async Socket Sample,没有等待形式MSDN

答案 1 :(得分:0)

您可以使用Dispatcher在单独的线程中启动Capture任务

Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{  
    try
    {       
        txtReadValue.Value = objRead.Capture();   
    }
    catch { } 
}