我有一个应用程序,它设置了一个 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/