簡體   English   中英

Qt QTimer以這種方式阻止它是否安全?

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

在它的“超時”信號/插槽功能中停止Qt的定時器是否安全? 似乎無法在Qt文檔中找到有關QTimer的任何信息。

我創建了一個定時向服務器發送“保持活動”消息的計時器。 如果在發送消息時出現某種錯誤,我希望停止此計時器。

private:
   QTimer* mpKeepAliveTimer;

Timer初始化如下:

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

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

mpKeepAliveTimer->start(KEEP_ALIVE_PERIOD);

像這樣停下來:

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

    delete mpKeepAliveTimer;
    mpKeepAliveTimer = NULL;
}

超時功能如下所示:

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

謝謝。

只要您沒有明確使用排隊連接,這是安全的。
這是因為在處理連接到的所有插槽之前, emit timeout()函數不會返回。

但是,如果您使用的是排隊連接,理論上可能會發生事件隊列中仍有未處理的超時事件,因此為了使其超安全,您可以使用以下命令:

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

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

請注意,stop函數中的條件應為!= NULL而不是== NULL 您也可以按如下方式編寫該函數:

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

正如評論中已經建議的那樣,QTimer將在其析構函數中停止運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM