这个有效。
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';
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
;相反,您可以检查
if Terminated then
Exit;
InternetReadFile
可以在循环中调用任意数量的字节进行获取。如果您将此与线程中的 Terminated 检查相结合,在关闭应用程序时标记线程以终止并等待线程终止,您就不会遇到任何“挂起”的情况。 - Lieven Keersmaekers