c# - 在线程内 sleep 的替代方法

标签 c# c++ multithreading delphi

各种答案表明在线程内休眠是个坏主意,例如: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/

相关文章:

c# - 尝试从预览运行屏幕保护程序时出现 SHIM_NOVERSION_FOUND 错误

c# - 根据配置使用不同的 assemblyNames 在 Visual Studio 2019 中进行调试

c# - 在没有 OleDbConnection 或 Interop 的情况下在 C# 中访问 Excel

c++ - 如何以编程方式将控制台字体设置为 Lucida?

c++ - cpp(15) : error C2182: 'input' : illegal use of type 'void'

c - 是什么限制了这个简单的 OpenMP 程序的扩展?

c# - NUnit 3.X.X 异步测试

c++ - boost Spirit 和 phoenix 解析为 std::string

java - 测试 final 字段的初始化安全性

javascript - 如何同步 JavaScript 回调?