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

Vin*_*vic 3 .net c# busy-loop

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

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

我现在正在做

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

这似乎工作(即捕获事件,并没有在繁忙的循环中使用核心).

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

AMi*_*ico 9

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

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

    Do
        Dim i As WaitForChangedResult = Me.FileSystemWatcher1.WaitForChanged(WatcherChangeTypes.All, 1000)
    Loop Until fCancel
Run Code Online (Sandbox Code Playgroud)

[update]"注意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;
        } 
    }
Run Code Online (Sandbox Code Playgroud)

[update]调用WaitForChangedSystem.Threading.Monitor.Wait语句之前和之后立即设置EnableRaisingEvents .


Ahm*_*aid 5

正如我从您的评论中所理解的,您需要您的应用程序无限期运行,它是一个由另一个可执行文件发送的控制台应用程序.

最好使用Console.ReadLine而不是循环.或使用Monitor.Wait方法无限期地阻塞线程

object sync = new object();
lock(sync)
Monitor.Wait(sync);
Run Code Online (Sandbox Code Playgroud)