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 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 theDisconnect()in its owntry/exceptblock if needed.