FileSystemWatcher和Invoke方法

时间:2011-02-05 05:03:27

标签: c#

我创建了一个CustomFileSystemWatcherClass,每当FileSystemWatcher事件发生时,我都会调用一个像树视图调用的函数,如

this.treeView.Invoke(....)

问题是当我使用Invoke时,FileSystemWatcher类没有正确处理 但是当我使用

this.treeView.BeginInvoke(....)

该类正在正确处置,但我只是出于其他原因使用Invoke

我可以知道如何解决这个问题吗?

这是Customfilesystemwatcher类

  class CustomFileSystemWatcher : FileSystemWatcher, IDisposable
  {
    private Timer timer;
    private Dictionary<string, DateTime> recentChange;
    private int interval = 500;
    public CustomFileSystemWatcher()
      : base()
    {
      InitializeMembers();
    }

    public CustomFileSystemWatcher(string Path)
      : base(Path)
    {
      InitializeMembers();
    }

    public CustomFileSystemWatcher(string Path, string Filter)
      : base(Path, Filter)
    {
      InitializeMembers();
    }
    public new event FileSystemEventHandler Changed;
    public int Interval
    {
      get
      {
        return this.interval;
      }
      set
      {
        this.interval = value;
      }
    }

    private void InitializeMembers()
    {
      this.timer = new System.Timers.Timer();
      this.recentChange = new Dictionary<string, DateTime>();
      this.timer.Interval = this.interval;
      this.timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimerElapsed);
      base.Changed += new FileSystemEventHandler(this.OnChanged);
    }

    private void HasAnotherFileEventOccuredRecently(FileSystemEventArgs e)
    {
        string fileName = e.FullPath;
        if (this.recentChange.ContainsKey(fileName))
          this.recentChange[fileName] = DateTime.Now;
        else
          this.recentChange.Add(fileName, DateTime.Now);
        if (!this.timer.Enabled)
          this.timer.Start();
    }
    protected new virtual void OnChanged(FileSystemEventArgs e)
    {
      if (this.Changed != null) this.Changed(this, e);
    }

    private void OnTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
      try
      {
        if (this.recentChange.Count != 0)
          lock (this.recentChange)
          {
            foreach (string key in this.recentChange.Keys.ToArray<string>())
            {
              if (this.recentChange.ContainsKey(key))
                if ((DateTime.Now.Ticks -
                        (this.recentChange[key]).Ticks) >=
                        new TimeSpan(0, 0, 0, 0, interval).Ticks)
                {
                  this.OnChanged(new FileSystemEventArgs(WatcherChangeTypes.Changed, this.Path,
                                 key.Replace(Path + "\\", "")));
                  this.recentChange.Remove(key);
                }
            }
          }
        if (this.recentChange.Count == 0)
          this.timer.Stop();
      }
      catch (Exception ex)
      {
      }
    }

    private void OnChanged(object sender, FileSystemEventArgs e)
    {
      this.HasAnotherFileEventOccuredRecently(e);
    }
    public new void Dispose()
    {
      base.Dispose();
    }
  }

0 个答案:

没有答案