0

我是 Qt 新手,目前正在学习使用QTcpServerQTcpSocket.

我处理数据的代码就像

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

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

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

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

4

1 回答 1

1

Qt will not pause your current work when data comes in, it will call processData() only when the event loop is free and waiting for new events.

so, when your application is busy executing your code, the application will appear to be unresponsive, because it can't respond to external events, so processData() won't get called if some data is received on the socket until the current function (that may contain your heavy code) returns, and the control is back in the event loop, that has to process the queued events (these events may contain the received data on the socket, or the user clicks on some QPushButton, etc) .

in short, that's why you always have to make your code as short and optimized as possible, in order not to block the event loop for a long time.

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!

see https://wiki.qt.io/Threads_Events_QObjects

于 2016-01-02T10:18:23.420 回答