So I created a class: TWorkerThread = class(TThread). In the TWorkerThread Constructor I set FreeOnTerminate := True.
I then added a private Worker variable to my TForm. When I instantiate TWorkerThread for Worker, I always use CreateSuspended := False.
The only interactions I need to have with the thread once started is to cancel the process (Terminate) and check if the process is over (that check is user event based).
To check if the thread is still active I do:
if (Self.Worker <> nil) and (not Self.Worker.Finished) then
//Still active
Which seems to work fine but I fear that at some time the TWorkerThread will be <> nil but still be .free (remember that TWorkerThread are all FreeOnTerminate := True). When a TWorkerThread "self destroy" once terminated do they always become nil? If not, how do I handle that (to avoid access violations)?
Another thing, if a Worker is active on it's form destroy, I do:
if (Self.Worker <> nil) and (not Self.Worker.Finished) then
begin
Self.Worker.Terminate;
//wait here for completion
end;
After the Terminate if I do a WaitFor I get an access violation (because of the self destroy). Should I enforce a wait here? Whats the best way to do it?
This is my first proper usage of TThread in Delphi. The code above is a skimmed down version of what I do for clarity.