QTcpSocket readyRead() 信号发出多次

QTcpSocket readyRead() signal emits multiple times

我是 Qt 的新手,目前正在学习使用 QTcpServerQTcpSocket 进行编码。

我处理数据的代码就像

Myclass() 
{
   connect(&socket, &QTcpSocket::readyRead, this, &MyClass::processData);
}

void MyClass::processData()
{
  /* Process the data which may be time-consuming */
}

这样使用信号的方法正确吗?当我阅读文档时,在同一线程中立即调用插槽,这意味着如果我的处理工作尚未完成并且有新数据到来,Qt 将暂停当前工作并再次进入 processData()。那不是我想要做的,所以我应该在 signal/slot 连接中 QueueConnection 吗?

或者能否请您提供一些在这种情况下我应该采用的好方法?

Qt 不会在数据进来时暂停您当前的工作,它只会在事件循环空闲并等待新事件时调用 processData()

因此,当您的应用程序正忙于执行您的代码时,应用程序会显得没有响应,因为它无法响应外部事件,因此如果收到某些数据,processData() 将不会被调用在套接字上直到当前函数(可能包含您的大量代码)returns,并且控件返回事件循环,必须处理排队的事件(这些事件可能包含套接字上接收到的数据,或者用户点击一些 QPushButton,等等)。

简而言之,这就是为什么您总是必须使代码尽可能简短和优化,以免长时间阻塞事件循环。

With the event delivery stuck, widgets won't update themselves (QPaintEvent objects will sit in the queue), no further interaction with widgets is possible (for the same reason), timers won't fire and networking communications will slow down and stop. Moreover, many window managers will detect that your application is not handling events any more and tell the user that your application isn't responding. That's why is so important to quickly react to events and return to the event loop as soon as possible!

https://wiki.qt.io/Threads_Events_QObjects