简体   繁体   English

Qt QTimer以这种方式阻止它是否安全?

[英]Qt QTimer is it safe to stop it this way?

Is it safe to stop Qt's timer in it's "timeout" signal/slot function? 在它的“超时”信号/插槽功能中停止Qt的定时器是否安全? Can't seem to find any information in Qt documentation about the QTimer . 似乎无法在Qt文档中找到有关QTimer的任何信息。

I have created a timer that is periodically sending a "keep alive" messages to the server. 我创建了一个定时向服务器发送“保持活动”消息的计时器。 I want this timer to be stopped if there is some kind of error while sending my message. 如果在发送消息时出现某种错误,我希望停止此计时器。

private:
   QTimer* mpKeepAliveTimer;

Timer is initialized like this: Timer初始化如下:

mpKeepAliveTimer = new QTimer(/* this */);

QObject::connect(mpKeepAliveTimer, SIGNAL(timeout()), this, SLOT(OnKeepAlive()));

mpKeepAliveTimer->start(KEEP_ALIVE_PERIOD);

Stopped like this: 像这样停下来:

if (mpKeepAliveTimer != NULL) // <-- Edited
{
    if (mpKeepAliveTimer->isActive() == true)
        mpKeepAliveTimer->stop();

    delete mpKeepAliveTimer;
    mpKeepAliveTimer = NULL;
}

Timeout function looks like this: 超时功能如下所示:

void Classname::OnKeepAlive()
{
   if (isErrorFound == true)
      mpKeepAliveTimer->stop();   // <---- IS THIS SAFE?
}

Thanks. 谢谢。

As long as you are not explicitly using Queued Connections, this is safe. 只要您没有明确使用排队连接,这是安全的。
This is because the emit timeout() function will not return until all the slots it's connected to were processed. 这是因为在处理连接到的所有插槽之前, emit timeout()函数不会返回。

If you were however using Queued Connections, it could in theory happen that there are still unprocessed timeout events in the Event Queue, so to make it hyper-safe you could use the following: 但是,如果您使用的是排队连接,理论上可能会发生事件队列中仍有未处理的超时事件,因此为了使其超安全,您可以使用以下命令:

void Classname::OnKeepAlive()
{
    if (!mpKeepAliveTimer || !mpKeepAliveTimer->isActive()) return;

    if (isErrorFound)
    {
        mpKeepAliveTimer->stop();
    }
}

Note that the condition in your stop function should be != NULL instead of == NULL . 请注意,stop函数中的条件应为!= NULL而不是== NULL You can also write that function as follows, however: 您也可以按如下方式编写该函数:

if (mpKeepAliveTimer)
{
    delete mpKeepAliveTimer;
    mpKeepAliveTimer = NULL;
}

As already suggested in the comments, QTimer will stop itself in its destructor. 正如评论中已经建议的那样,QTimer将在其析构函数中停止运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM