Reputation: 141
Is it safe to override Free method? I'm asking because I would like to use something like this. I know it's very ugly to use TerminateThread, but in my case it's very critical to kill the process with all its threads immediately.
I've seen the __free method declared in System.pas, but I don't know if it has something to do with the TObject.Free method and that's the reason why I'm asking if it's safe.
type
TMyThread = class(TThread)
private
destructor Destroy; override;
public
procedure Execute; override;
constructor Create;
procedure Free(const Force: Boolean = False); // is it safe to use this?
end;
procedure TMyThread.Free(const Force: Boolean = False);
begin
if not Force then
begin
Terminate;
WaitFor;
end
else
TerminateThread(Handle, 0);
inherited Free;
end;
destructor TMyThread.Destroy;
begin
// free resources etc.
inherited Destroy;
end;
Thank you
Upvotes: 3
Views: 1369
Reputation: 16620
You can't override Free
because it's not virtual. If you define your own Free
method it will hide the TObject.Free
method (note the compiler warning) if the static type is your class type. This is definitely not a good idea since the object will then never get destroyed.
I don't see any reason why you want to do that. If you really want to use TerminateThread
then just give your thread class another method ForceTerminate
, in which you call TerminateThread
.
Upvotes: 10