【问题标题】:FileSystemWatcher locks file, how to release it?FileSystemWatcher 锁定文件,如何释放?
【发布时间】:2016-08-28 13:11:24
【问题描述】:

当在 Paint 上编辑图像文件并使用它更新预览图像控件时,我正在使用 FileSystemWatcher 引发事件。但是第二次将文件设置为源,它会引发错误,因为该文件仍在被另一个进程使用。所以我发现这是因为 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,但没有成功。我该怎么做?

【问题讨论】:

    标签: wpf filesystemwatcher


    【解决方案1】:

    文件既没有被 FileSystemWatcher 锁定,也没有被 MS Paint 锁定。实际发生的是你得到了一个InvalidOperationException,因为FileSystemWatcher 的Changed 事件没有在UI 线程中触发,因此处理程序方法不能设置Image 控件的Source 属性。

    在 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);
            }
        }));
    }
    

    【讨论】:

    • 谢谢,它成功了。但是not fired in the UI Thread 是什么意思?您能否给我一个更详细的解释以获取逻辑。这对我很重要。再次感谢。
    • 你可以阅读Dispatcher类的在线文档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2018-12-19
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多