我有一个控制台应用程序需要监视特定目录并等待所有文件在特定时间内被删除。 如果超过该时间并且还没有删除所有文件,我需要该程序抛出异常。我怎么能做到这一点?
public static void FileWatcher(string fileName, int timeToWatch)
{
FileSystemWatcher watcher = new FileSystemWatcher();
try
{
watcher.Path = myPath;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = string.Format("*{0}*", fileName);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
catch
{
throw;
}
}
答案 0 :(得分:0)
您可以使用Task.Delay
设置超时(我假设timeToWatch
以毫秒为单位,如果没有,则相应地更改它)。如果目录没有更多文件(不检查子文件夹),则将其他任务设置为已完成。该方法将阻止(WaitAny
),直到发生超时或文件全部被删除。如果需要,可以很容易地将其更改为async
。
public static void FileWatcher(string fileName, int timeToWatch)
{
FileSystemWatcher watcher = new FileSystemWatcher();
var timeout = Task.Delay(timeToWatch);
var completedTcs = new TaskCompletionSource<bool>();
watcher.Path = myPath;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = string.Format("*{0}*", fileName);
watcher.Deleted += (s, e) => OnChanged(myPath, timeout, completedTcs);
watcher.EnableRaisingEvents = true;
OnChanged(myPath, timeout, completedTcs);
// Wait for either task to complete
var completed = Task.WaitAny(completedTcs.Task, timeout);
// Clean up
watcher.Dispose();
if (completed == 1)
{
// Timed out
throw new Exception("Files not deleted in time");
}
}
public static void OnChanged(string path, Task timeout, TaskCompletionSource<bool> completedTcs)
{
if (!Directory.GetFiles(path).Any())
{
// All files deleted (not recursive)
completedTcs.TrySetResult(true);
}
}