以前写的一段代码,可以参考一下,确实不复杂的。
unit DownThread;
interface
uses
Classes, SysUtils, IdComponent, IdHTTP;
type
TEventType = (etStatus, etWork, etWorkBegin, etWorkEnd);
TDTCallBackEvent = procedure(AThreadID: THandle; AEventType: TEventType; AThreadInfo: string) of object;
TDownThread = class(TThread)
private
FFileUrl: string;
FFileSaveName: string;
FDTCallBackEvent: TDTCallBackEvent;
FEventType: TEventType;
FThreadInfo: string;
procedure HTTPStatus(axSender: TObject; const axStatus: TIdStatus;
const asStatusText: string);
procedure HTTPWork(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCount: Integer);
procedure HTTPWorkBegin(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCountMax: Integer);
procedure HTTPWorkEnd(Sender: TObject; AWorkMode: TWorkMode);
procedure DoDTCallBackEvent(AEventType: TEventType; AThreadInfo: string);
procedure DoCallBack;
public
constructor Create(AFileUrl, AFileSaveName: string; CreateSuspended: Boolean = False);
procedure Execute; override;
property DTCallBackEvent: TDTCallBackEvent read FDTCallBackEvent write FDTCallBackEvent;
end;
implementation
{ TDownThread }
constructor TDownThread.Create(AFileUrl, AFileSaveName: string;
CreateSuspended: Boolean);
begin
FFileUrl := AFileUrl;
FFileSaveName := AFileSaveName;
FreeOnTerminate := True;
inherited Create(CreateSuspended);
end;
procedure TDownThread.DoCallBack;
begin
if Assigned(FDTCallBackEvent) then
FDTCallBackEvent(Handle, FEventType, FThreadInfo);
end;
procedure TDownThread.DoDTCallBackEvent(AEventType: TEventType; AThreadInfo: string);
begin
FEventType := AEventType;
FThreadInfo := AThreadInfo;
SYNCHRONIZE(DoCallBack);
end;
procedure TDownThread.Execute;
var
Stream: TStream;
begin
Stream := TFileStream.Create(FFileSaveName, fmCreate);
try
with TIdHTTP.Create(nil) do
try
OnStatus := HTTPStatus;
OnWork := HTTPWork;
OnWorkBegin := HTTPWorkBegin;
OnWorkEnd := HTTPWorkEnd;
Get(FFileUrl, Stream);
finally
Free;
end;
finally
Stream.Free;
end;
end;
procedure TDownThread.HTTPStatus(axSender: TObject;
const axStatus: TIdStatus; const asStatusText: string);
begin
DoDTCallBackEvent(etStatus, asStatusText);
end;
procedure TDownThread.HTTPWork(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCount: Integer);
begin
DoDTCallBackEvent(etWork, IntToStr(AWorkCount));
end;
procedure TDownThread.HTTPWorkBegin(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCountMax: Integer);
begin
DoDTCallBackEvent(etWorkBegin, IntToStr(AWorkCountMax));
end;
procedure TDownThread.HTTPWorkEnd(Sender: TObject; AWorkMode: TWorkMode);
begin
DoDTCallBackEvent(etWorkEnd, Format('任务完成:(%s ==> %s)', [FFileUrl, FFileSaveName]));
end;
end.
调用:
procedure TFormMain.Button2Click(Sender: TObject);
begin
with TDownThread.Create(Edit1.Text, Edit2.Text, True) do
begin
//DTCallBackEvent := ThreadStatus;
Resume;
end;
end;