1. 程式人生 > 實用技巧 >Delphi 執行緒Thread釋放的方式

Delphi 執行緒Thread釋放的方式

Delphi 執行緒Thread釋放的方式

1、執行緒的釋放方式:

  • 停止後 自動釋放
  • 手動停止後 自動釋放
  • 手動釋放。

注意:如果執行緒已經停止並且自動釋放,再去手動停止,就會報錯。

2、程式碼示例:

2.1、停止後自動釋放的執行緒(FreeOnTerminate := True;):

constructor TMyThread.Create; 
begin 
  inherited Create( True ); 
  FreeOnTerminate := True; 
end; 

procedure TMyThread.Execute; 
begin 
  //功能程式碼 
  //此方法完成後執行緒就已經停止了 
end; 

2.2、手動停止後自動釋放的執行緒:

constructor TMyThread.Create; 
begin 
  inherited Create( True ); 
  FreeOnTerminate := True; 
end; 

procedure TMyThread.Execute; 
begin 
  while not Terminated do //not Terminated do 
  begin 
     //功能程式碼 
  end; 
end; 

procedure Test 
begin 
  Thread1 := TMyThread.Create( Self ); 
  Thread1.Terminate; 
end; 

2.3、手動釋放的執行緒:

constructor TMyThread.Create; 
begin 
  inherited Create( True ); 
end; 

procedure TTestThread.Execute; 
begin 
  while not Terminated do //not Terminated do 
  begin 
    //功能程式碼 
  end; 
end; 

procedure Test 
begin 
  Thread1 := TMyThread.Create( Self ); 
  Thread1.Terminate; 
  Thread1.WaitFor;   //等待執行緒執行完成
  Thread1.Free; 
end;

建立時間:2020.07.31  更新時間: