各种答案表明在线程内休眠是个坏主意,例如:Avoid sleep .为什么呢?经常给出的一个原因是,如果线程正在休眠,则很难优雅地退出线程(通过发出终止信号)。
假设我想定期检查网络文件夹中的新文件,可能每 10 秒一次。这对于优先级设置为低(或最低)的线程来说似乎是完美的,因为我不希望可能耗时的文件 I/O 影响我的主线程。
有哪些选择?代码在 Delphi 中给出,但同样适用于任何多线程应用程序:
procedure TNetFilesThrd.Execute();
begin
try
while (not Terminated) do
begin
// Check for new files
// ...
// Rest a little before spinning around again
if (not Terminated) then
Sleep(TenSeconds);
end;
finally
// Terminated (or exception) so free all resources...
end;
end;
一个小的修改可能是:
// Rest a little before spinning around again
nSleepCounter := 0;
while (not Terminated) and (nSleepCounter < 500) do
begin
Sleep(TwentyMilliseconds);
Inc(nSleepCounter);
end;
但这仍然涉及 sleep ......
最佳答案
执行此操作的标准方法是等待取消事件。在看起来像这样的伪代码中:
while not Terminated do
begin
// Check for new files
// ...
// Rest a little before spinning around again
FTerminationEvent.WaitFor(TenSeconds);
end;
为了终止你会覆盖TerminatedSet
:
procedure TMyThread.TerminatedSet;
begin
inherited;
FTerminationEvent.SetEvent; // abandon the wait in the thread method
end;
事件等待超时,或终止,因为事件已发出信号。这允许您的线程暂停一段时间而不会给 CPU 带来负担,同时还能对终止请求保持响应。
关于c# - 在线程内 sleep 的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33960620/