判断函数 :function CheckThreadFreed(aThread: TThread): Byte; 具体使用如下:
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TMyThread = class(TThread)//自定义的线程
protected
procedure Execute; override;
end;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
mytd: TMyThread;//线程对像
implementation
{$R *.dfm}
//返回值:0-已释放;1-正在运行;2-已终止但未释放;3-未建立或不存在
function CheckThreadFreed(aThread: TThread): Byte;
var
I: DWord;
IsQuit: Boolean;
begin
if Assigned(aThread) then
begin
IsQuit := GetExitCodeThread(aThread.Handle, I);
if IsQuit then //If the function succeeds, the return value is nonzero.
//If the function fails, the return value is zero.
begin
if I = STILL_ACTIVE then //If the specified thread has not terminated,
//the termination status returned is STILL_ACTIVE.
Result := 1
else
Result := 2; //aThread未Free,因为Tthread.Destroy中有执行语句
end
else
Result := 0; //可以用GetLastError取得错误代码
end
else
Result := 3;
end;
procedure TMyThread.Execute;
var
I: Integer;
begin
for I := 0 to 500000 do
begin
Form1.Canvas.Lock;
Form1.Canvas.TextOut(10, 10, IntToStr(I));
Form1.Canvas.Unlock;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if CheckThreadFreed(mytd)<>1 then //判断线程是否存在
begin
mytd := TMyThread.Create(True);
mytd.FreeOnTerminate := True;
mytd.Resume;
end;
end;
end.

















