Search code examples
delphimultithreadingindy

Errors with Indy in threaded application !


I've got some memories leak related to TidHTTP when it's waiting for the response of a server after a GET and that the thread is being terminated.

Example :

aThread = class(TThread) 
private  
  FidHTTP :TidHTTP;   
  FCommand :String;
public   
  procedure Execute(); override;   
  constructor Create(aCommand :String); override;
  procedure Disconnect;
end;

procedure aThread.Execute();   
  var response :String; 
begin   
  response := FidHTTP.Get(FCommand); 
end;

procedure aThread.Disconnect;
begin
  if ((FidHTTP <> nil) and (FidHTTP.Connected)) then FidHTTP.IOHandler.CloseGracefully;
end;

constructor aThread.Create(aCommand :String); override; 
begin   
  FCommand := aCommand;    
  inherited Create; 
end;

I stop the thread with this when the application close :

aThread.Disconnect;
aThread.Terminate;
aThread.Free;

What should I do to solve the memories leaks ?

FastMM4 Log :

13 - 20 bytes: TIdThreadSafeInteger x 1
21 - 36 bytes: EAccessViolation x 1, TIdCriticalSection x 2
181 - 212 bytes: UnicodeString x 1

Thanks :)


Solution

  • You should call

    aThread.WaitFor;
    

    before destroying the thread. This makes sure that the thread properly terminates. Destroying the thread without terminating it probably causes an access violation in the execute method, which results in the memory leaks displayed by FastMM.

    EDIT Considering the fact that the problem might be the blocking call in your execute method, you might want to set TIdHttp.ReadTimeOut to a reasonable time and check for thread termination in regular intervals.