Given this example, how do we ensure that the thread instance has been freed? What happens to the thread instance when Thread.FreeOnTerminate=true and you blow up in your Thread.OnTerminate event? Is the thread orphaned unless you handle the exception and free the thread explicitey in OnTerminate?
// Thread constructor
constructor TMyThread.Create(CreateSuspended: Boolean);
begin
inherited Create(CreateSuspended);
Self.FreeOnTerminate := True;
end;
// TMyThread OnTerminate event
procedure TMyThread.OnTerminate(Sender: TObject);
var o: TObject;
begin
o:=nil;
showmessage(o.classname); // guaranteed AV
end;
You should handle all exceptions in your OnTerminate handler because an unhandled exception will cause that the instance of the thread will not be freed (see
Classes.ThreadProcimplementation).Just enclose the body of your handler in
try..exceptand handle all exceptions.But your example for ‘guaranteed AV’ is wrong:
Freedoes not cause an AV if the instance is nil.