冰玉天星 發表於 2020-7-31 14:17:00

Delphi 线程Thread释放的方式

<p><span style="font-size: 16px"><strong>Delphi 线程Thread释放的方式</strong></span></p>
<p><span style="font-size: 16px"><strong>1、线程的释放方式:</strong></span></p>
<ul>
<li><span style="font-size: 16px">停止后 自动释放</span></li>
<li><span style="font-size: 16px">手动停止后 自动释放</span></li>
<li><span style="font-size: 16px">手动释放。</span></li>
</ul>
<p><span style="font-size: 16px">注意:如果线程已经停止并且自动释放,再去手动停止,就会报错。</span></p>
<p>&nbsp;</p>
<p><span style="font-size: 16px"><strong>2、代码示例:</strong></span></p>
<p><span style="font-size: 16px"><strong>2.1、停止后自动释放的线程(FreeOnTerminate := True;):</strong></span></p>
<div class="cnblogs_Highlighter">
<pre class="brush:delphi;gutter:true;"><span style="font-size: 16px">constructor TMyThread.Create;
begin
inherited Create( True );
FreeOnTerminate := True;
end;

procedure TMyThread.Execute;
begin
//功能代码
//此方法完成后线程就已经停止了
end; </span></pre>
</div>
<p><span style="font-size: 16px"><strong>2.2、手动停止后自动释放的线程:</strong></span></p>
<div class="cnblogs_Highlighter">
<pre class="brush:delphi;gutter:true;"><span style="font-size: 16px">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; </span></pre>
</div>
<p><span style="font-size: 16px"><strong>2.3、手动释放的线程:</strong></span></p>
<div class="cnblogs_Highlighter">
<pre class="brush:delphi;gutter:true;"><span style="font-size: 16px">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;
</span></pre>
</div>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p><span style="color: rgba(136, 136, 136, 1)">创建时间:2020.07.31  更新时间:</span></p>
<p>&nbsp;</p>

</div>
<div id="MySignature" role="contentinfo">
    博客园 滔Roy https://www.cnblogs.com/guorongtao 希望内容对你有所帮助,谢谢!<br><br>
来源:https://www.cnblogs.com/guorongtao/p/13409437.html
頁: [1]
查看完整版本: Delphi 线程Thread释放的方式