简体   繁体   中英

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? Can't seem to find any information in Qt documentation about the 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:

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.

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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