我在一个线程中使用TIdHTTP.Get
过程下载文件。我的问题是如何停止(取消)文件的下载?
我会尝试在TIdHTTP.OnWork事件中使用Abort方法抛出一个静默异常来取消它。这个事件会在读写操作时触发,所以它也会在你的下载进度中触发。
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;
OnWorkHandler
事件中调用FIdHTTP.Disconnect
是否更好? - Salvador