2010-01-08 83 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,你不需要任何锁定。