等待使用 FileSystemWatcher 删除所有文件

Wait for all files to be deleted using FileSystemWatcher

我有一个控制台应用程序需要监视特定目录并等待所有文件在特定时间内被删除。 如果超过该时间并且所有文件尚未删除,我需要程序抛出异常。我怎样才能做到这一点?

    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;
        }
    }

您可以使用 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);
    }
}