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

发布于 2024-11-27 12:37:30 字数 67 浏览 0 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

碍人泪离人颜 2024-12-04 12:37:30

我会尝试通过使用 Abort 方法抛出静默异常来取消它 < a href="http://www.indyproject.org/docsite/html/frames.html?frmname=topic&frmfile=TIdTCPConnection_OnWork.html" rel="noreferrer">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;

或者正如这里提到的,要直接断开连接,您可以使用

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

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;
夜夜流光相皎洁 2024-12-04 12:37:30

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文