This Works。
var
DownloadAbort: boolean;
procedure Download(const URL, FileName: string);
var
hInet: HINTERNET;
hURL: HINTERNET;
Buffer: array[0..1023] of AnsiChar;
BufferLen, amt: cardinal;
f: file;
const
UserAgent = 'Delphi Application'; // Change to whatever you wish
begin
DownloadAbort := false;
hInet := InternetOpen(PChar(UserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
try
hURL := InternetOpenUrl(hInet, PChar(URL), nil, 0, 0, 0);
try
FileMode := fmOpenWrite;
AssignFile(f, FileName);
try
Rewrite(f, 1);
repeat
InternetReadFile(hURL, @Buffer, SizeOf(Buffer), BufferLen);
BlockWrite(f, Buffer[0], BufferLen, amt);
if DownloadAbort then
Exit;
until BufferLen = 0;
finally
CloseFile(f);
end;
finally
InternetCloseHandle(hURL);
end;
finally
InternetCloseHandle(hInet);
end;
end;
在實踐中,上面的代碼將是你的線程的Execute
方法的一部分,而你並不需要DownloadAbort
; intead,你檢查
if Terminated then
Exit;
的'InternetReadFile'可以在一個循環中獲取字節任意數量的調用。如果將它與線程中的Terminated檢查組合在一起,請在關閉應用程序時標記線程以終止並等待線程終止,則不應該有任何「掛起」。 – 2010-08-23 14:47:52