Author: Lou Adler
Let's say that once I start a thread up, I pop up a progress window that has a
cancel button on it to cancel execution of the thread. How do I implement this?
Answer:
To exit a thread created with TThread mid-process (as in a loop), break out of the
loop and immediately call Terminate. This sets the Terminated flag to true.
Following the loop you should check the Terminated status in the body of the
Execute method; something like this:
1 procedure Execute;
2 begin3 //...some stuff4 while SomeCondition do5 begin6 // ...do some stuff7 if CancelFlagOfSomeSort then8 begin9 Terminate;
10 Break;
11 end;
12 end;
13 if MyTThread.Terminated then14 Exit;
15 end;
It's important to call Terminate because it will trigger the OnTerminate event,
that'll allow your thread to clean up after itself. If you just break out of the
thread and don't release resources, you'll create orphan resources in memory, and
that is not a good thing to do.
For plain-vanilla threads, all you have to do is exit out of the thread function. That will "kill" the thread. But remember that in either case, the most important thing you have to remember is to free resources that you use during the course of the run. If you don't they'll stay there and occupy memory.