c# - 每 100 毫秒检查一次响应

标签 c# .net tcp response tcpclient

我制作了这个 TCP 客户端并且它正在工作但是当它检查传入流时它会暂停应用程序...(源代码 - 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();
        }

最佳答案

您的方法 check() 会“暂停”应用程序,因为它的作业当前正在 UI 线程中执行。

如果您不希望您的方法卡住 UI,您应该在不同于 UI 线程的后台线程中安排该方法的执行。

您可以使用 BackgroundWorker 来做到这一点线。正如@qujck 所建议的,一个例子是 here .

关于c# - 每 100 毫秒检查一次响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21647711/

相关文章:

c# - 从字符串中删除具有某种模式的子字符串

http - Erlang:接受连接时出现奇怪的滞后

c - 将文件从服务器复制到客户端

c# - 在 XNA 中使用 Draw 方法旋转 Texture2D?

c# - 如何创建一个基于xsd文件接收和发送xml的web服务?

c# - 将小数简化为分数的算法

java - HTTP Keep-Alive 可以维持长轮询吗?

c# - 使用 FakeItEasy 的 Winrt 测试项目

c# - 添加 IdentityUser 作为其他模型的属性

ASP.Net Core静态文件安全(特别是图像)