c# - 在 C# 中创建空闲循环的好方法?

标签 c# .net busy-loop

我有一个应用程序,它设置了一个 FileSystemWatcher。它应该无限期地运行。

让它在空闲循环中运行的最佳方法是什么?

我现在正在做

FileSystemWatcher watch = ... //setup the watcher
watch.EnableRaisingEvents = true;
while (true) 
{
    Thread.Sleep(int.MaxValue);
}

这似乎有效(即捕获事件并且不会在繁忙的循环中用完核心)。

还有其他成语吗?这种方法有什么问题吗?

最佳答案

FileSystemWatcher.WaitForChanged 是阻塞(同步)。 绝对不需要空闲循环,尤其是因为您正在处理事件。注意 EnableRaisingEvents 默认为 true。因此,您所要做的就是将组件添加到表单中。没有空闲循环。没有线程,因为组件会处理它。

我了解到您正在使用控制台应用程序。因此,您可以创建以下循环。同样,不需要空闲循环。该组件负责所有细节。

    Do
        Dim i As WaitForChangedResult = Me.FileSystemWatcher1.WaitForChanged(WatcherChangeTypes.All, 1000)
    Loop Until fCancel

[更新]“注意 EnableRaisingEvents 默认为 true。”根据 Microsoft 源代码,只有将 FileSystemWatcher 组件放到设计器上时才会出现这种情况。如下图:

    /// <internalonly/>
    /// <devdoc>
    /// </devdoc>
    [Browsable(false)] 
    public override ISite Site {
        get { 
            return base.Site; 
        }
        set { 
            base.Site = value;

            // set EnableRaisingEvents to true at design time so the user
            // doesn't have to manually. We can't do this in 
            // the constructor because in code it should
            // default to false. 
            if (Site != null && Site.DesignMode) 
                EnableRaisingEvents = true;
        } 
    }

[更新] 调用 WaitForChanged 会在 System.Threading.Monitor.Wait 语句前后立即设置 EnableRaisingEvents。

关于c# - 在 C# 中创建空闲循环的好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1420601/

相关文章:

cpu-usage - 为什么繁忙循环会占用 100% 的 CPU?

c# - 保存图像时如何找到一般 GDI+ 错误的原因?

c# - 一对多和递归关系 - 要设置的强制值

.net - 体面的低占用空间Web服务器? (。网)

.net - TCP星型网络对等连接策略

.net - conhost.exe 貌似内存泄漏

java - 为什么小于15ms的busy-wait不一致?

concurrency - 在 erlang 中轮询接收 block 是好的做法吗?

c# - 元编程 : write in one language X, C#、PHP、Java、C 等多种语言交叉编译

c# - 通过代理使用 UnityWebRequest 的 REST 连接