6

I'm using the TIdHTTP.Get procedure in a thread to download a file . My question is how I can stop (cancel) the download of the file?

Salvador
  • 16,132
  • 33
  • 143
  • 245

2 Answers2

13

I would try to cancel it by throwing an silent exception using Abort method in the TIdHTTP.OnWork event. This event is fired for read/write operations, so it's fired also in your downloading progress.

type
  TDownloadThread = class(TThread)
  private
    FIdHTTP: TIdHTTP;
    FCancel: boolean;
    procedure OnWorkHandler(ASender: TObject; AWorkMode: TWorkMode; 
      AWorkCount: Integer);
  public
    constructor Create(CreateSuspended: Boolean);
    property Cancel: boolean read FCancel write FCancel;
  end;

constructor TDownloadThread.Create(CreateSuspended: Boolean);
begin
  inherited Create(CreateSuspended);
  FIdHTTP := TIdHTTP.Create(nil);
  FIdHTTP.OnWork := OnWorkHandler;
end;

procedure TDownloadThread.OnWorkHandler(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCount: Integer);
begin
  if FCancel then
  begin
    FCancel := False;
    Abort;
  end;
end;

Or as it was mentioned here, for direct disconnection you can use Disconnect method in the same event.

procedure TDownloadThread.OnWorkHandler(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCount: Integer);
begin
  if FCancel then
  begin
    FCancel := False;
    FIdHTTP.Disconnect;
  end;
end;
  • does not will better call `FIdHTTP.Disconnect` from inside of the `OnWorkHandler` event? – Salvador Aug 03 '11 at 07:56
  • @Salvador - surely will in case you won't keep connection from the FIdHTTP anymore. The important is to do it in the [OnWork](http://www.indyproject.org/docsite/html/frames.html?frmname=topic&frmfile=TIdTCPConnection_OnWork.html) event to interrupt the downloading at progress time. –  Aug 03 '11 at 14:03
  • 3
    You can't abort a request midway and expect to leave the connection open, you don't know what state you are leaving the socket in or what data has already been transmitted. There is no way to clear an HTTP connection and leave it open for a new request. The only sane thing to do is close the connection. – Remy Lebeau Jun 14 '16 at 22:10
5

You could use the default procedure idhttp1.Disconnect...

opc0de
  • 11,557
  • 14
  • 94
  • 187