Salvador
Salvador

Reputation: 16492

How stop (cancel) a download using TIdHTTP

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?

Upvotes: 6

Views: 5436

Answers (2)

user532231
user532231

Reputation:

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;

Upvotes: 14

opc0de
opc0de

Reputation: 11768

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

Upvotes: 5

Related Questions