delphi判斷線程狀態

判斷函數 :function CheckThreadFreed(aThread: TThread): Byte;
具體使用以下:
api

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.
相關文章
相關標籤/搜索