FileSystemWatcher 锁定文件,如何释放它?

FileSystemWatcher locks file, how to release it?

我正在使用 FileSystemWatcher 在 Paint 上编辑图像文件时引发事件并使用它更新预览图像控件。但是第二次将文件设置为源时,它会抛出错误,因为该文件仍在被另一个进程使用。所以我发现这是因为 FileSystemWatcher。

我有这个代码:

    private void btnEdit_Click(object sender, RoutedEventArgs e)
    {
        if (!File.Exists(lastImage)) return;
        FileSystemWatcher izleyici = new FileSystemWatcher(System.IO.Path.GetDirectoryName( lastImage),
            System.IO.Path.GetFileName(lastImage));
        izleyici.Changed += izleyici_Changed;
        izleyici.NotifyFilter = NotifyFilters.LastWrite;
        izleyici.EnableRaisingEvents = true;
        ProcessStartInfo info = new ProcessStartInfo();
        info.FileName = lastImage;
        info.Verb = "edit";
        Process.Start(info);
    }

    void izleyici_Changed(object sender, FileSystemEventArgs e)
    {
       //I want to add code here to release the file. Dispose() not worked for me

       setImageSource(lastImage);
    }

    void setImageSource(string file)
    {
        var bitmap = new BitmapImage();

        using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad;
            bitmap.StreamSource = stream;
            bitmap.EndInit();
        }

        ssPreview.Source = bitmap;
    }

在这段代码中,我想在更新 Image 控件之前释放文件。我试过 Dispose 但没有成功。我该怎么做?

文件既没有被 FileSystemWatcher 锁定,也没有被 MS Paint 锁定。实际发生的是您得到一个 InvalidOperationException,因为 FileSystemWatcher 的 Changed 事件没有在 UI 线程中触发,因此处理程序方法无法设置图像控件的 [=13] =] 属性.

在 Dispatcher 操作中调用图像加载代码解决了问题:

void setImageSource(string file)
{
    Dispatcher.Invoke(new Action(() =>
    {
        using (var stream = new FileStream(
                                file, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            ssPreview.Source = BitmapFrame.Create(
                stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
        }
    }));
}