Hello At my form I create TFrame at runtime. At this frame I create background thread with executes commands in endless loop. But when I destroy this frame I should destroy this thread. I try
thread.Suspend;
thread.Terminate;
FreeAndNil(thread);
but get AV and ThreadError. How should i destroy thread?
You must make sure that the thread exits its Execute
method to terminate it properly.
Code could be something like this:
procedure TThread.Execute;
begin
while not Self.Terminated do
begin
//do something
end;
end;
Call this when You want to destroy thread:
thread.Terminate;
thread.WaitFor;
FreeAndNil(thread);
It is sufficient to do thread.Terminate
. But you will probably want to set thread.FreeOnTerminate := true
when it is created.
Of course, in the tight loop of your thread (that is, in Execute
), you need to check if the thread has been requested to terminate (check the Terminated
property). If you find that the thread has been requested to terminate, simply break from the loop and exit from Execute
.
You should never call suspend on a tthread its not safe to do so and resume should only be used to start a thread that was created suspended.
In Delphi 2010 the suspend and resume where depreciated and the method start was introduced to reinforce this.
For a more complete explanation see this thread at Codegears forums.
having said that there are 2 ways I will terminate and free a tthread.
1: I Set FreeOnTerminate when the thread is created so I just call.
Thread.Terminate;
2: Free the thread explicitly, as I need to read a result from a public property before the thread is freed and after it has terminated.
Thread.Terminate;
Thread.WaitFor;
//Do somthing like read a public property from thread object
if Thread <> nil then FreeAndNil(Thread);
In the main execute loop it may be a good idea to put some exception handling in. Or you may be left wondering why the thread appears to terminate its self. This may be causing the AV if the thread is set to FreeOnTerminate and it has already been freed when you try to free it.
procedure TThread.Execute;
begin
while not Terminated do
begin
try
//do something
except
on E:Exception do
//handle the exception
end;
end;
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With