How stop (cancel) a download using TIdHTTP

2019-02-10 21:33发布

问题:

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?

回答1:

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



回答2:

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;


标签: delphi indy