<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body text="#000000" bgcolor="#FFFFFF">
Is there a way to use FreeOnTerminate other that setting it in the
constructor (or before the thread starts / or in the rather complex
manner below)?<br>
<br>
The doc does not mention any limitations
<a class="moz-txt-link-freetext" href="https://www.freepascal.org/docs-html/rtl/classes/tthread.freeonterminate.html">https://www.freepascal.org/docs-html/rtl/classes/tthread.freeonterminate.html</a><br>
<br>
However, setting FreeOnTerminate*after* Execute() has finished has
no effect.<br>
<br>
So code like:<br>
<pre> t := TThread.create(false); // create not suspended
// do something
if foo then begin // decide we do not need the result
t.FreeOnTerminate:= true;
t.terminate;
end;</pre>
<br>
This may fail. If the thread's execute already finished, then the
thread is not destroyed.<br>
The code cannot call WaitFor, because the thread could still be
running for a long time. And even take a long time until it
recognizes the "terminate" request.<br>
So the app wants just to signal it, and tell it to clean up after
itself.<br>
<br>
But in the above code, if Execute() had already finished, t is never
destroyed. (tested with 3.0.4)<br>
<br>
One would have to test for Finished in addition. Only that Finished
could change between it being queried and any subsequent action.<br>
So the only solution I can see is maybe<br>
<br>
<pre> t := TThread.create(false); // create not suspended
// do something
if foo then begin // decide we do not need the result
t.Suspend;
if t.Finished then begin
t.free; // Not sure, since it is finished, we would not need to Terminate, WaitFor or Resume ?
t := nil;
end
else begin
t.FreeOnTerminate:= true;
t.terminate;
t.Resume;
t := nil; // no longer save to access
end;
end;</pre>
<br>
1) Is there an easier way?<br>
2) Should the doc have any hint towards this?<br>
3) Should FreeOnTerminate maybe detect this situation itself?<br>
<br>
</body>
</html>