3

场景是我有一个根文件夹来监视任何新文件夹(包含文件)并设置一个计时器来单独压缩每个文件夹。但是,我无法判断文件夹中的文件是否是调用 zip 函数之前的最后一个文件,因此,只要在压缩文件夹之前创建了新文件,我就想将计时器重置到该文件夹​​。

FileSystemWatcher用来监视根文件夹及其子文件夹。

  1. 我不确定如何创建另一个观察者来监视文件的创建,也许是在 OnTimedEvent 方法中。
  2. 一旦检测到该文件夹​​的文件,我不知道如何重置计时器。我认为也是在 OnTimedEvent 中编写代码来重置它。

下面是我尝试的代码的一部分,源代码可以在这里找到。任何帮助将不胜感激。

    public class FileWatcher
    { 
     private FileSystemWatcher _watcherRoot;
     private Timer _timer;
     private readonly string _watchedPath;

    public FileWatcher(string path)
    {
        // _watcher = new FileSystemWatcher();
        _timer = new Timer();
        _watchedPath = path;


        InitWatcher();
    }

    public void InitWatcher()
    {
        _watcherRoot = new FileSystemWatcher();
        _watcherRoot.Path = _watchedPath;
        _watcherRoot.IncludeSubdirectories = true;
        _watcherRoot.EnableRaisingEvents = true;
        _watcherRoot.Created += new FileSystemEventHandler(OnCreated);

    }

    private void OnCreated(object sender, FileSystemEventArgs e)
    {

        if (e.ChangeType == WatcherChangeTypes.Created)
        {
            string fullPath = e.FullPath;
            if (sender == _watcherRoot)
            {
                // If detect new folder, set the timer to 5 sec
                _timer.Interval = 5000;
                _timer.Elapsed += OnTimedEvent;
                _timer.AutoReset = true;
                _timer.Enabled = true;

                // a directory
                Console.WriteLine($"{fullPath.ToString()} created on {DateTime.Now}");
            }

        }
    }

    private void OnTimedEvent(object sender, ElapsedEventArgs e)
    {
        // Create a 2nd Watcher??
        // Reset the timer in here??
    }
4

3 回答 3

1

在这里,您有一个简单的扩展方法来重置给定的计时器。

  public static void Reset(this Timer timer)
    {
      timer.Stop();
      timer.Start();
    }

要从事件内部获取计时器对象,您需要强制sender转换System.Timers.Timer()或仅在静态上下文中使用计时器。

于 2018-10-31T13:54:25.477 回答
1

有一个名为Reactive Extensions的非常聪明的库,最初由 Microsoft 编写为“Rx”,但现在放置在“System.Reactive”命名空间中。它允许您非常简单地编写复杂的事件驱动代码。

例如,在您所描述的场景中,您可以对FileSystemWatcher的事件“做出反应”并使用反应式“油门”,这意味着您只会在该事件发生一段时间后收到事件通知没有发生。您还可以将多个不同的事件合并在一起。把这两个特性放在一起,然后订阅你的方法。

如果这听起来像是一个可能的解决方案,您可能想看看Intro to Rx,这里有一个与解决此问题的方法相关的问题,包括在各种答案中执行此操作的大约 4 种方法:Wrap a file watcher在响应式扩展中(这不是该问题的重复,因为您在询问计时器,我建议您可能想要使用响应式扩展)。

于 2018-11-03T18:00:18.047 回答
0

我有点使用 lambda 表达式来解决这个问题,将计时器和观察者“绑定”在一起,这就是我发现的与这篇文章类似的内容。

于 2018-11-11T03:47:56.493 回答