I have a thread defined THttpThread
for downloading of a file. I would like to stop the download if modal form is closed or if Cancel button is pressed.
In the example from bellow I got Access Violation probably because of the way how I reuse the thread.
procedure Tform_update.button_downloadClick(Sender: TObject);
var
HttpThread: THttpThread;
begin
//download
if button_download.Tag = 0 then
begin
HttpThread:= THttpThread.Create(True);
//...
HttpThread.Start;
end
//cancel download
else
begin
HttpThread.StopDownload:= True;
end;
end;
I sow the answers from How stop (cancel) a download using TIdHTTP and some many others but I still don't get it how to update a property of a running thread.
I will give the answer found, using also the hints from users comments.
The access violation comes from the fact HttpThread
was not assigned during cancellation. Reason why HttpThread: THttpThread
must be defined under his form like:
Tform_update = class(TForm)
//...
private
HttpThread: THttpThread;
and then the code should be:
procedure Tform_update.button_downloadClick(Sender: TObject);
begin
//download
if button_download.Tag = 0 then
begin
HttpThread:= THttpThread.Create(True);
//...
HttpThread.Start
end
//cancel download
else
begin
if Assigned(HttpThread) then HttpThread.StopDownload:= True;
end;
end;
Same for form close
procedure Tform_update.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Assigned(HttpThread) then HttpThread.StopDownload:= True;
end;
As some users ask for in some comments, there is no need for the code of thread.