c# – 替代线程内部的睡眠

前端之家收集整理的这篇文章主要介绍了c# – 替代线程内部的睡眠前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
各种答案都表明在一个线程内睡觉是一个坏主意,例如: Avoid sleep.为什么这么做?经常给出的一个原因是,如果正在休眠,很难优雅地退出线程(通过发信号通知它终止).

假设我想定期检查网络文件夹中的新文件,可能每10秒检查一次.这对于优先级设置为低(或最低)的线程来说似乎是完美的,因为我不希望可能耗时的文件I / O影响我的主线程.

有哪些替代方案?代码在Delphi中给出,但同样适用于任何多线程应用程序:

  1. procedure TNetFilesThrd.Execute();
  2. begin
  3. try
  4. while (not Terminated) do
  5. begin
  6. // Check for new files
  7. // ...
  8.  
  9. // Rest a little before spinning around again
  10. if (not Terminated) then
  11. Sleep(TenSeconds);
  12. end;
  13. finally
  14. // Terminated (or exception) so free all resources...
  15. end;
  16. end;

一个小修改可能是:

  1. // Rest a little before spinning around again
  2. nSleepCounter := 0;
  3. while (not Terminated) and (nSleepCounter < 500) do
  4. begin
  5. Sleep(TwentyMilliseconds);
  6. Inc(nSleepCounter);
  7. end;

但这仍然涉及睡眠……

解决方法

执行此操作的标准方法是等待取消事件.在伪代码中看起来像这样:
  1. while not Terminated do
  2. begin
  3. // Check for new files
  4. // ...
  5.  
  6. // Rest a little before spinning around again
  7. FTerminationEvent.WaitFor(TenSeconds);
  8. end;

要终止,您将覆盖TerminatedSet:

  1. procedure TMyThread.TerminatedSet;
  2. begin
  3. inherited;
  4. FTerminationEvent.SetEvent; // abandon the wait in the thread method
  5. end;

事件的等待时间超时,或因事件发出信号而终止.这允许您的线程暂停一段时间而不会给cpu带来负担,同时还能保持对终止请求的响应.

猜你在找的C#相关文章