如何使用TIdHTTP停止(取消)下载

时间:2011-08-03 07:04:30

标签: delphi indy

我在线程中使用TIdHTTP.Get过程来下载文件。我的问题是如何停止(取消)下载文件?

2 个答案:

答案 0 :(得分:10)

我会尝试在Abort事件中使用TIdHTTP.OnWork方法抛出一个无声异常来取消它。此事件是为读/写操作触发的,因此它也会在您的下载过程中触发。

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;

或者如此处所述,对于直接断开连接,您可以在同一事件中使用Disconnect方法。

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

答案 1 :(得分:3)

您可以使用默认程序idhttp1.Disconnect ...