Multithreading 如何拥有我创建的所有线程的IDTCPClient列表?

Multithreading 如何拥有我创建的所有线程的IDTCPClient列表?,multithreading,delphi,thread-safety,delphi-xe3,Multithreading,Delphi,Thread Safety,Delphi Xe3,我创建了一个线程 type ss_thread = class; ss_thread = class(TThread) protected Fff_id : string; Fff_cmd : string; Fff_host : string; Fff_port : TIdPort; procedure Execute; override; public constructor Create(const ff_id, ff_c

我创建了一个线程

type 
  ss_thread = class;

  ss_thread = class(TThread)
  protected
    Fff_id : string;
    Fff_cmd : string;
    Fff_host : string;
    Fff_port : TIdPort;
    procedure Execute; override;
  public
    constructor Create(const ff_id, ff_cmd: string; ff_host: string; ff_port: TIdPort);
  end;

constructor ss_thread.Create(const ff_id, ff_cmd: string; ff_host: string; ff_port: TIdPort);
begin
  inherited Create(False);
  Fff_id   := ff_id;
  Fff_cmd  := ff_cmd;
  Fff_host := ff_host;
  Fff_port := ff_port;
end;

...
id := 123; // dynamic
...

nst_ss_thread.Create(id, cmd, host, port);
在上面做点什么

procedure ss_thread.Execute;
var
  ws : TIdTCPClient;
  data : TIdBytes;
  i : integer;
  list : TList;
begin
      ws := TIdTCPClient.Create(nil);
      ws.Host := Fff_host;
      ws.Port := Fff_port;
....
我有主线程,它接收来自其他源的数据,我需要将所有数据转发到我的线程,并将我接收到的ID转发到“ws”IdTCPClient

如何拥有我创建的所有线程的IDTCPClient列表


谢谢

将它们存储在线程列表中

ClientList: TThreadList<TIdTCPClient>;
ClientList:TThreadList;
在创建任何客户端之前,先创建其中一个对象

ClientList := TThreadList<TIdTCPClient>.Create;
ClientList:=TThreadList.Create;
无论何时创建客户端,都要添加它:

procedure ss_thread.Execute;
var
  List: TList<TIdTCPClient>;
....
ws := TIdTCPClient.Create(nil);
List := ClientList.LockList;
try
  List.Add(ws);
finally
  ClientList.UnlockList;
end;
程序ss_thread.Execute;
变量
名单:TList ;;
....
ws:=TIdTCPClient.Create(nil);
列表:=ClientList.LockList;
尝试
列表。添加(ws);
最后
ClientList.UnlockList;
结束;
无论何时需要迭代客户端,都可以这样做:

var
  List: TList<TIdTCPClient>;
  Client: TIdTCPClient;
....
List := ClientList.LockList;
try
  for Client in List do
    // do something with Client
finally
  ClientList.UnlockList;
end;
var
名单:TList ;;
客户:TIdTCPClient;
....
列表:=ClientList.LockList;
尝试
对于列表中的客户,请执行以下操作:
//和客户做点什么
最后
ClientList.UnlockList;
结束;

在线程的析构函数中,您还需要从列表中删除客户端。

我也正打算建议:)在向列表中添加/删除TidtcpClient时以及在发送时要小心异常-由于套接字的异步状态,在某些阶段几乎不可避免。在线程的析构函数中(在继承的调用之前)找到它并从
ClientList
中删除。您可以通过某些方式减少异常,例如,通过强制所有线程通过受CS保护的状态机访问套接字/列表,但我不确定这是否值得。@TLama-是的,但这可能太晚了,无法阻止发送线程尝试写入死套接字等等不管怎样,仍在处理异常:(@TLama:I将重写线程的
DoTerminate()
方法,而不是使用析构函数,以从列表中删除
TIdTCPClient
,并释放
TIdTCPClient