【问题标题】:Closing a Client thread gracefully优雅地关闭客户端线程
【发布时间】:2011-11-15 20:23:44
【问题描述】:

我正在对 Delphi 7 Indy9 轮询客户端进行故障排除。我尝试添加带有waitforsingleobject 的 TEvent 以及许多其他优雅断开连接的方法。错误发生在 readln 中。该错误通常是“EIDConnection...未连接”。我已经对其进行了监视,并且线程终止了。但是“while”在连接从服务器接收到消息之前不会重新评估条件,所以它只是在readln 处进行研磨,直到它接收到一个消息。所以有时它会优雅地断开连接,但大多数时候会崩溃。有没有办法做到这一点,或者我只是试一试......除了在 r​​eadln 周围并继续......提前谢谢

procedure TReadingThread.Execute;
begin
    while not Terminated and FConn.Connected do
    begin
        // read msg from server
        Msg := FConn.ReadLn;
        Synchronize(ReceiveLine); 
    end;
end;

【问题讨论】:

  • 实际问题是什么?如果连接关闭,ReadLn() 在设计上应该引发异常。删除对Connected() 的调用,让ReadLn() 完成它的工作。如果您让异常终止线程(这将是正确的做法),则 while 应该 not 继续运行,因为异常会跳出循环。所以我不明白你到底遇到了什么问题。

标签: delphi delphi-7


【解决方案1】:

我认为您需要添加一些代码来处理 Disconnect 事件。我遇到了与您描述的类似的问题,这就是我所做的(在此示例中,tcpServer 是 TIdTCPServer 的实例):

    procedure TformRemoteControlWnd.tcpServerDisconnect(AContext: TIdContext);
    (*
    Connection is disconnected. Be careful, because this also gets called when
    the app is shutting down while a connection is active, in which case
    tcpServer may be gone already.
    *)
    begin
      if not Application.Terminated and Assigned(tcpServer) then
      begin
        sbarStatus.SimpleText := 'TCP/IP Disconnected';
        tcpServer.Tag := 0; // used to prevent rentrancy
      end;

      // shut down connection to stop thread from calling OnExecute event
      try
        AContext.Connection.Disconnect;
      except
        Sleep(0);
      end;
    end;

【讨论】:

  • 一旦为某个连接触发了OnDisconnect 事件,就不会再为该连接触发OnExecute 事件。一旦OnDisconnect 处理程序退出,连接将被关闭。无需在OnDisconnect 事件处理程序中调用Disconnect()
  • 雷米 - 谢谢,我试试看。那是不久前的事了,但我似乎记得我必须将 Disconnect() 调用放在那里是有原因的。
【解决方案2】:

我找到了答案...Readln 将无限期地等待,直到收到回车。因此,线程位于Readln,直到服务器发送消息或套接字断开连接(这会导致崩溃)。在 Delphi 编译器代码中,OnDisconnect 中写入了一条注释,以使用 try...except 捕获错误。所以我只需要在断开套接字之前小心清理。我想我可以找到一个更干净的关闭方法。感谢所有的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-29
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多