TIdTCPServer.Active := False的研究

http://blog.csdn.net/jadeluo/article/details/3958423

原创 2009年03月05日 08:31:00

设置TIdTCPServer的Active为False的这个操作存在着一些问题:

1. 在设置Active为False时, 将结束所有已连接的客户端线程(PeerThread), 这个结束操作是有超时检测的(超时的时长可以通过TerminateWaitTime属性进行设置)。如果超时, 则抛出超时异常,这个异常在Delphi的IDE环境中无法屏蔽,给调试程序带来很多不便。而且,出现超时异常时,TIdTCPServer并未正常关闭,还得再次设置Active为False。

2. 从设置Active为False开始到所有PeerThread线程结束或者抛出超时异常,主进程将阻塞,主进程的界面将无响应。

这些问题都是让人不能接受的。

 

研究了一下Indy的源码,写了下面这段代码,来解决TIdTCPServer.Active := False的问题。

 

 

[delphi] view plain copy
 
  1. uses IdThreadSafe;   //需要引用IdThreadSafe单元  
  2.   
  3. ......  
  4.   
  5. var  
  6.   AList: TList;  
  7.   iLoop: Integer;  
  8. begin  
  9.   if Assigned(IdTCPServer1.Threads) then  
  10.   begin  
  11.     AList := IdTCPServer1.Threads.LockList;  
  12.     try  
  13.       for iLoop := to AList.Count -do  
  14.       begin  
  15.         TIdPeerThread(AList.Items[iLoop]).Connection.Disconnect;  
  16.         TIdPeerThread(AList.Items[iLoop]).Stop;  
  17.       end;  
  18.     finally  
  19.       IdTCPServer1.Threads.UnlockList;  
  20.     end;  
  21.     while not TIdThreadSafeList(IdTCPServer1.Threads).IsCountLessThan(1) do  
  22.     begin  
  23.       Application.ProcessMessages;  
  24.       Sleep(100);  
  25.     end;  
  26.   end;  
  27.   IdTCPServer1.Active := False;  
  28. end;