Hello,
I know this question has been asked before, but I'm still struggling with it. I'm looking for the proper way for all four cases dealing with thread termination:
a) FreeOnTerminate=False, thread terminates internally (e.g. exception, finished, etc.)
b) FreeOnTerminate=True, thread terminates internally
c) FreeOnTerminate=False, thread being terminated by calling Terminate
d) FreeOnTerminate=True, thread being terminated by calling Terminate
No matter what I do, I run into problems. As far as I have read meanwhile, it is common practice for cases b) and d), i.e. when using FreeOnTerminate, to have an OnTerminate handler which sets the thread reference to NIL so that I can be sure to have a valid reference to the thread.
But now, in case d) I cannot use FThread.Terminate;
FThread.WaitFor;
because the thread might get freed in between. Obviously, pepople work around this problem by setting FThread.FreeOnTerminate:=false before using the "Terminate - WaitFor - Free" cascade. Is this correct?
In case c), I get sporadic access violations in the WaitFor instruction. Very bad. So from this point of view, it seems better to enable FreeOnTerminate because this seems to free the thread most reliably. But it causes heavy problems on the other hand because the thread cannot be stopped and freed proberly when closing the program. I get a wild mixture of access violations and memory leaks when trying to do this.
The WaitFor instruction on the other hand waits forever if the thread hasn't been started. Very bad because there's actually no need to wait in this case.
So what is the actual best practice to terminate a thread? Should FreeOnTerminate be enabled or disabled? How to deal with WaitFor?