如标题所示,为什么以下代码执行两次(在控制台中为2x Test
),以及如何解决该问题?
type
TSelfThread = class(TThread)
procedure Execute; override;
end;
procedure TSelfThread.Execute;
begin
Writeln('Test');
end;
var
SelfThread : TSelfThread;
begin
try
SelfThread := TSelfThread.Create(False);
except
on E: Exception do
Writeln('Error');
end;
end.
答案 0 :(得分:2)
对此行为的唯一可能解释是代码中的错误,在该错误中,您无法等待线程完成才终止进程。
将代码更改为这样:
SelfThread := TSelfThread.Create(False);
SelfThread.WaitFor;