我制作了这个 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/