FileSystemWatcher处理调用挂起

Sco*_*man 10 .net c# filesystemwatcher winforms

我们刚刚开始使用FileSystemWatcher遇到一个奇怪的问题,其中对Dispose()的调用似乎是挂起的.这段代码一段时间没有任何问题,但我们刚刚升级到.NET3.5 SP1,所以我试图找出是否有其他人看到过这种行为.以下是创建FileSystemWatcher的代码:

if (this.fileWatcher == null)
{
   this.fileWatcher = new FileSystemWatcher();
}
this.fileWatcher.BeginInit();
this.fileWatcher.IncludeSubdirectories = true;
this.fileWatcher.Path = project.Directory;
this.fileWatcher.EnableRaisingEvents = true;
this.fileWatcher.NotifyFilter = NotifyFilters.Attributes;
this.fileWatcher.Changed += delegate(object s, FileSystemEventArgs args)
{
   FileWatcherFileChanged(args);
};
this.fileWatcher.EndInit();
Run Code Online (Sandbox Code Playgroud)

使用它的方法是更新TreeNode对象的状态图像(稍微调整以删除特定于业务的信息):

private void FileWatcherFileChanged(FileSystemEventArgs args)
{
   if (this.TreeView != null)
   {
      if (this.TreeView.InvokeRequired)
      {
         FileWatcherFileChangedCallback d = new FileWatcherFileChangedCallback(FileWatcherFileChanged);
         this.TreeView.Invoke(d, new object[]
      {
         args
      });
      }
      else
      {
         switch (args.ChangeType)
         {
            case WatcherChangeTypes.Changed:
               if (String.CompareOrdinal(this.project.FullName, args.FullPath) == 0)
               {
                  this.StateImageKey = GetStateImageKey();
               }
               else
               {
                  projectItemTreeNode.StateImageKey = GetStateImageKey();
               }
               break;
         }
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

有没有我们遗漏的东西,或者这是.NET3.5 SP1的异形?

Jon*_*upp 7

只是一个想法...这里有任何机会出现死锁问题吗?

你正在调用TreeView.Invoke,这是一个阻塞调用.如果文件系统发生变化就像你点击任何导致FileSystemWatcher.Dispose()调用的按钮一样,你的FileWatcherFileChanged方法将在后台线程上调用并调用TreeView.Invoke,它将阻塞,直到你的表单线程可以处理Invoke请求.但是,表单线程将调用FileSystemWatcher.Dispose(),在处理完所有挂起的更改请求之前,它可能不会返回.

尝试将.Invoke更改为.BeginInvoke,看看是否有帮助.这可能有助于指明您正确的方向.

当然,它也可能是.NET 3.5SP1问题.我只是根据你提供的代码推测这里.