Reputation:
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?
Upvotes: 1
Views: 3881
Reputation: 596352
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.
Upvotes: 5