簡體   English   中英

服務器等待響應期間Qt客戶端應用程序停止

[英]Qt Client application halt during waiting response from server

問題 :
使用While循環檢查條件,如果在指定時間內沒有收到服務器的響應,則使用計時器。

操作系統: Linux
SDK: QT 5.5

描述:

我已經實現了一個客戶端,並且在代碼中有while循環,該循環不斷檢查某些條件(“檢查機器已啟動”)是否為真。 當它從機器Server得到一些消息時,這種情況就會改變。 當我實現while循環時,它會卡在其中,並且不會出來。 我在這個論壇上解雇了Question,有人好心地向我指出了我的錯誤,他建議我應該使用QStateMachine,因為我的while循環正在消耗我的所有資源。

因此,在深入研究狀態機時,我碰到了QCoreApplication :: processEvents()。 當我在我的代碼中添加它時,所有內容均按預期工作,但計時器部分仍然超時。 現在我的問題是

1)QStateMachine和QCoreApplication :: processEvents()之間有什么區別?哪個更好。

2)如何正確使用QTimer,以便在規定的時間內,如果while循環中的條件不成立,則超時並跳過while循環。

void timerStart( QTimer* timer, int timeMillisecond )
    {
      timer = new QTimer( this );
      connect( timer, SIGNAL( timeout() ), this, SLOT( noRespFrmMachine( ) ) ) ;
      timer->start( timeMillisecond );
    }

    void timerStop( QTimer* timer )
    {
      if( timer )
        {
          timer->stop();
        }
    }

    void noRespFrmMachine( )
    {
      vecCmd.clear();
    }

    void prepareWriteToMachine()
    {
         // Some other code
          //  check if Machine has started we will get response in MainWindow and
          // it will update isMachineStarted so we can check that
          QTimer *timer ;
          timerStart( timer, TIMEOUT_START ); // IS THIS RIGHT??
          while( isMachineStarted() == false  )  // getMachineRunning-> return isMachineStarted ??
            {
              // do nothing wiat for machine server to send machine_started signal/msg
         QCoreApplication::processEvents(); // added this one and my aplication is responsive and get correct result

            }
          if( isMachineStarted() == true )
            {
              // if we are here it mean timer has not expired & machine is runing
              // now check for another command and execute
              timerStop( timer );
              while( vecCmd.size() > 0 )
                {
                  QString strTemp = returnFrontFrmVec();
                  setStoreMsgFrmCliReq( strTemp );
                  reconnectToServer();
                }
            }
        }
    }

timerStop( timer ); 應該會造成分段錯誤。 函數timerStart不會更改prepareWriteToMachine()的局部變量timer ,因此該變量包含未定義的垃圾。

如果要在timerStart更改外部變量timer ,則應將指向QTimer指針傳遞給該函數:

void timerStart(QTimer**timer, int timeMillisecond)
{
    *timer = new QTimer(this);
    ...
}

順便說一句,由於在任何情況下都不timerStop() timer設置為零,因此在timerStop()中檢查if( timer ) timerStop()意義。

暫無
暫無

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

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