2010-01-08 86 views
0

我正在模擬器中測試連接和命令發送到服務器。模擬器有一些櫃檯等發送的命令共成功發送的命令,不能發送的命令,連接嘗試,成功連接,等等在模擬器中計數連接和命令(Delphi 7/Windows XP)

,我使用的代碼如下:

procedure TALClient.SendCommand; 
begin 
    Try 
    dlgMain.IncrementIntConx; //Increments conn attemps 
    FTCP.Connect(1000); 
    If FTCP.Connected Then 
     Begin 
     dlgMain.IncrementConections; //increments successfully connections 

     try 
      dlgMain.IncrementIntSendCommand; //Increments command sent attemps (A) 
      FTCP.SendCmd(FCmd.FNemo + ' ' + FCmd.FParams); // (Z) 
      dlgMain.IncrementSendComm; //Increments sent Commands (B) 

      try 
      FParent.CS.Acquire; 
      FParent.FStatistic[Tag, FCmd.FTag].LastCodeResult := FTCP.LastCmdResult.NumericCode; 
      FParent.FStatistic[Tag, FCmd.FTag].LastMsgResult := FTCP.LastCmdResult.Text.Text; 
      FParent.CS.Release; 
      if ((FTCP.LastCmdResult.NumericCode) = (497)) then 
       Synchronize(UpdateCorrectCounters) //increments successfully responds from server 
      else 
       Synchronize(UpdateErrorCounters); //increments failed responds from server 
      except 
      Synchronize(UpdateErrorCounters); 
      end; 

     except 
      dlgMain.IncrementFailCommand; //increments failed commands (C) 
     end; 
     End 
    Else 
     Synchronize(UpdateErrorCounters); //Increment failed responses from sever 
    Finally 
    If FTCP.Connected Then 
     FTCP.Disconnect; 
    End 
end; 

我已經將代碼更改爲許多其他許多方式,但它永遠不會正常工作。 最大的問題是發送命令的總數不等於發送命令成功發送,發送命令失敗。 (在代碼中:A不等於B加C)。有沒有在標記爲(Z)的行中「看到」,也許是「丟失」響應的響應...

那麼,我在做什麼錯了?

回答

1

我想你正在爲你的模擬器使用多個線程。這看起來像經典丟失更新問題給我。你必須同步反遞增的代碼。

遞增的變量是線程安全:

Temp := CounterValue; 
// If another thread intercepts here, we've got a lost update 
Temp := Temp + 1; 
CounterValue := Temp; 

看到這個MSDN article閱讀更多關於併發問題。

1

如果你只使用計數,你可以使用Windows功能InterlockedIncrementInterlockedDecrement,你不需要任何鎖定。