简体   繁体   中英

Terminate a thread and disconnect an indy client

In Delphi I have a threaded client that listens for response in a thread. Thread is declared like:

TMyThread = class(TThread)
  private
    FClient: TIdTCPClient;
    FStringResponse: string;
  protected
    procedure Execute; override;
    procedure DoSynch;
  public
    constructor Create(AClient: TIdTCPClient);
  end;

I connect using the:

  if not IdTCPClient1.Connected then
  begin
    // // Set the Host
    IdTCPClient1.Host := Edit1.Text;
    // // Set the port
    IdTCPClient1.Port := 65535;
    // // Connect
    IdTCPClient1.Connect;
    try
      MyThread := TMyThread.Create(IdTCPClient1);
    except
      IdTCPClient1.Disconnect;
      raise;
    end;
  end;

I try to disconnect using:

if MyThread <> nil then
  begin
    MyThread.Terminate;
    // MyThread.WaitFor;
    MyThread.Free;
    MyThread := nil;
    IdTCPClient1.Disconnect;
end;

But this disconnect code throws an exception. What's the proper way to do terminate this thread and to disconnect the client?

Try reversing the order of your shutdown operations - disconnect the client before freeing the thread, rather than the opposite. That way, any blocking socket operation inside the thread is aborted immeidately, allowing the thread to react to the termination:

if MyThread <> nil then
  MyThread.Terminate; 
try
  IdTCPClient1.Disconnect; 
finally
  if MyThread <> nil then
  begin
    MyThread.WaitFor; 
    MyThread.Free; 
    MyThread := nil; 
  end;
end; 

If you are still getting an exception from Disconnect() , then make sure the thread is not disconnecting the client, only reading/writing from it, and wrap the Disconnect() in its own try/except block if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM