我有一个线程类来做一些工作,然后向主应用程序线程发布一条消息并自行终止。这样做的正确方法是什么,我需要一个 OnTerminate 过程还是析构函数就足够了?
(线程列表与问题有点无关,我想用它来检查有多少线程仍在工作)
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.