AFileSystemWatcher
不需要线程或 Windows 服务。只需创建它,设置您的事件处理程序,然后设置EnableRaisingEvents
为 true。然后启动一个在 10 分钟后到期的计时器并处理观察者。就像是:
private async void RunAfterDelay(TimeSpan delay, CancellationToken token, Action action)
{
await Task.Delay(delay, token);
if (!token.IsCancellationRequested)
{
action();
}
}
private void RunWatcher()
{
var cts = new CancellationTokenSource();
var watcher = new FileSystemWatcher();
watcher.Path = "...";
watcher.Created += (_, e) =>
{
if (e.FullPath == "file-you-are-interested-in")
{
// cancel the timer
cts.Cancel();
// do your stuff
// ...
// get rid of the watcher
watcher.Dispose();
}
};
watcher.EnableRaisingEvents = true;
// start the timer
RunAfterDelay(TimeSpan.FromMinutes(10), cts.Token, () =>
{
// get rid of the watcher
watcher.Dispose();
// do anything else you want to do, like send out failure notices.
});
}
这将开始监听观察者,如果你得到你想要的,它将处理观察者。如果计时器到期,它将停止观察者。
以上是针对.NET 4.5。如果您的目标是 4.0,那么首先获取Delay
此处显示的实现:https ://stackoverflow.com/a/9068520/674326
然后改成RunAfterDelay
这样:
private void RunAfterDelay(TimeSpan delay, CancellationToken token, Action action)
{
TaskEx.Delay(delay, token).ContinueWith(t => action(), TaskContinuationOptions.OnlyOnRanToCompletion);
}