I have a thread class to do some work then post a message to the main app thread and self terminate. What's the correct way to do this, do I need an OnTerminate procedure or is the Destructor enough?
(The threads List is a bit irrelevant to the question, I want to use it to check how many threads are still working)
FThread := TPicBuilder.Create(PicObject);
FThread.Resume;
.
Type TPicBuilder = class(TThread)
protected
procedure Execute; override;
private
MyPic: TBitmap32;
procedure AddToPool;
procedure RemoveFromPool;
procedure MyTerminateHandler(Sender: TObject);
public
Constructor Create(Pic: Pointer);
Destructor Destroy; override;
end;
Var PicThreads: TObjectList<TPicBuilder>;
implementation
Constructor TPicBuilder.Create(Pic: Pointer);
begin
inherited Create(False);
Self.FreeOnTerminate := True;
Self.OnTerminate := MyTerminateHandler;
MyPic:= TBitmap32(Pic);
Synchronize(AddToPool);
end;
Destructor TPicBuilder.Destroy;
begin
inherited Destroy;
Synchronize(RemoveFromPool);
// PostMessage(Application.Handle, WM_APicBuilt, 0 {some tag goes here with a pic ID}, 0); // should I call this here instead?
end;
procedure TPicBuilder.AddToPool;
begin
PicThreads.Add(Self);
end;
procedure TPicBuilder.RemoveFromPool;
begin
PicThreads.Remove(Self);
end;
procedure TPicBuilder.MyTerminateHandler(Sender: TObject);
begin
PostMessage(Application.Handle, WM_APicBuilt, 0, 0);
end;
Procedure TPicBuilder.Execute;
begin
// thread work
end;
Initialization
PicThreads := TObjectList<TPicBuilder>.Create(False);
Finalization
PicThreads.Free;
end.