繁体   English   中英

等待使用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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM