Creating a thread in a class derived from the thread

advertisements

I created a new class derived from TThread class, and on the constructor i call "inherited Create(True);", and then call "Resume()" since i have override the Execute() call, now i wanna recall the Execute() (Run the Thread Again) without destroying the class instance, so i have a function inside the new class called "myRestart()", which recalls "inherited Create(True);" and makes me able to call "Resume()" again and thread works again.

my question is, is this a safe practice? will it work also if i have multiple instances of this class? or is there a better way to do it?

thanks


Don't go around doing things like that. If you want procedures/functions in your thread class to run more than once, call them from a while() loop in your Execute override and signal the thread to run the code with a suitable synchro object at the top, a semaphore or event, say:

TmyThread.Execute;
begin
  while true do
  begin
    someEvent.waitFor(INFINITE);
    if terminated then exit;
    doMyProcedure(params);
    doOtherStuff;
  end;
end;