Mirror

Interrupt a thread's execution (Views: 100)


Problem/Question/Abstract:

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:

procedure Execute;
begin
  //...some stuff
  while SomeCondition do
  begin
    // ...do some stuff
    if CancelFlagOfSomeSort then
    begin
      Terminate;
      Break;
    end;
  end;
  if MyTThread.Terminated then
    Exit;
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.

<< Back to main page