在TThread.Execute中加入无限循环是不好的做法?

Sal*_*dor 10 delphi multithreading

我写了一个Thread.descendent类,并在execute方法中我放了一个无限循环来监听一个com事件,被认为是一个糟糕的线程练习使用无限循环来做到这一点?应用程序工作正常,不冻结,总是响应,我只是回答因为我想使用最好的方法来线程化.

procedure TMyThread.Execute;
begin
    while True and not Terminated do
    begin
     AResult:= FListener.GetResult(Param1,Param2,5000);
      if not VarIsNull(AResult) then
        Synchronize(Process);
    end;
end;
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 14

编译器将其转换为:

while not Terminated do
Run Code Online (Sandbox Code Playgroud)

当这样写出来时,我相信你会同意它看起来很自然.这是一个非常常见的习语.


Gol*_*rol 7

这样做是可以的.你正在检查Terminated,这很好.如果你的监听器允许它并且你的CPU使用率太高,你可以通过在其中放置Sleep(1)来减慢你的线程,但我认为没有必要.

  • 虽然它在技术上还可以,但它完全没有必要,并且使代码更难阅读.正如@David Heffernan指出的那样,"真实而非终止"等同于"未终止",第二种更容易阅读.(但不是低估,因为它*在技术上是正常的,即使它是多余的和无用的.) (5认同)