每100ms检查一次响应

时间:2014-02-08 15:17:09

标签: c# .net tcp response tcpclient

我创建了这个TCP客户端并且它正在工作但是当它检查传入的流时它会暂停app ...(源代码 - https://app.box.com/s/7ly47ukztlo5eta3wqbk) 这是那部分:

        void check()
        {
            if (tcpclnt.Connected == true)
            {
                NetworkStream stm2 = tcpclnt.GetStream();
                if (stm2.CanRead)
                {
                    // Reads NetworkStream into a byte buffer. 
                    byte[] bytes = new byte[tcpclnt.ReceiveBufferSize];

                    // Read can return anything from 0 to numBytesToRead.  
                    // This method blocks until at least one byte is read.
                    stm2.Read(bytes, 0, (int)tcpclnt.ReceiveBufferSize);

                    // Returns the data received from the host to the console. 
                    string returndata = Encoding.UTF8.GetString(bytes);

                    log("SERVER: " + Environment.NewLine + returndata + Environment.NewLine);
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            check();
        }

1 个答案:

答案 0 :(得分:1)

您的方法check()'暂停'应用,因为其作业当前在UI线程中执行。

如果您不希望您的方法冻结UI,则应该在后台线程中安排方法的执行,这与您的UI线程不同。

您可以使用BackgroundWorker主题执行此操作。 @qujck建议的一个例子是here