在使用delphi做開發(fā)時(shí),使用線程可以從TThread繼續(xù),然后覆蓋execute方法,這樣我們的線程類就OK了,在execute寫上要處理的代碼就可以。當(dāng)線程的執(zhí)行從execute退出時(shí)線程也就結(jié)束了,這能正確的釋放建立tthread時(shí)的一些資源,如果加while not terminated do...end中執(zhí)行,調(diào)用terminate其實(shí)也是一個(gè)道理。delphi中線程結(jié)束代碼如下:
try
if not Thread.Terminated then
try
Thread.Execute;
except
Thread.FFatalException := AcquireExceptionObject;
end;
finally
FreeThread := Thread.FFreeOnTerminate;
Result := Thread.FReturnValue;
Thread.DoTerminate;
Thread.FFinished := True;
SignalSyncEvent;
if FreeThread then Thread.Free;
EndThread(Result);
end;
EndThread時(shí)線程即被結(jié)束。通過代碼看到如果execute發(fā)生異常也是能正常釋放資源的,因?yàn)橥鈱佑袀€(gè)更大的tryf。假如我們通過terminatethread結(jié)束線程那么是不會(huì)執(zhí)行finally中代碼的,資源便不會(huì)釋放。進(jìn)程中加載的dll也不會(huì)收到線程結(jié)束的通知。如果長(zhǎng)期這樣結(jié)束,會(huì)導(dǎo)致創(chuàng)建線程時(shí)報(bào)"thread creation error. 系統(tǒng)內(nèi)存不足,無(wú)法處理此命令"。
聯(lián)系客服