I'm usi开发者_JAVA技巧ng the TIdHTTP.Get
procedure in a thread to download a file . My question is how I can stop (cancel) the download of the file?
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;
You could use the default procedure idhttp1.Disconnect...
精彩评论