【问题标题】:Release handle on file. ImageSource from BitmapImage释放文件上的句柄。来自 BitmapImage 的 ImageSource
【发布时间】:2012-04-25 16:06:23
【问题描述】:

如何释放这个文件的句柄?

img 是 System.Windows.Controls.Image 类型

private void Load()
{
    ImageSource imageSrc = new BitmapImage(new Uri(filePath));
    img.Source = imageSrc;
    //Do Work
    imageSrc = null;
    img.Source = null;
    File.Delete(filePath); // File is being used by another process.
}

解决方案


private void Load()
{
    ImageSource imageSrc = BitmapFromUri(new Uri(filePath));
    img.Source = imageSrc;
    //Do Work
    imageSrc = null;
    img.Source = null;
    File.Delete(filePath); // File deleted.
}



public static ImageSource BitmapFromUri(Uri source)
{
    var bitmap = new BitmapImage();
    bitmap.BeginInit();
    bitmap.UriSource = source;
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.EndInit();
    return bitmap;
}

【问题讨论】:

  • 不错的解决方案。你拯救了我的一天:)
  • 这 3 行是什么:img.Source = imageSrc; //做工作 imageSrc = null; img.Source = null;
  • @MonsterMMORPG 不用担心它们... bitmap.CacheOption = BitmapCacheOption.OnLoad;是神奇的部分。

标签: c# wpf xaml


【解决方案1】:

在 MSDN 论坛上找到了答案。

位图流不会关闭,除非缓存选项设置为 BitmapCacheOption.OnLoad。所以你需要这样的东西:

public static ImageSource BitmapFromUri(Uri source)
{
    var bitmap = new BitmapImage();
    bitmap.BeginInit();
    bitmap.UriSource = source;
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.EndInit();
    return bitmap;
}

当你使用上面的方法得到一个 ImageSource 时,源文件 将立即关闭。

see MSDN social forum

【讨论】:

  • 如果我使用这段代码,应用程序的内存增加有什么变化吗?
【解决方案2】:

在一个特别令人不安的图像上,我一直遇到这个问题。接受的答案对我不起作用。

相反,我使用流来填充位图:

using (FileStream fs = new FileStream(path, FileMode.Open))
{
    bitmap.BeginInit();
    bitmap.StreamSource = fs;
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.EndInit();
}

这导致文件句柄被释放。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    相关资源
    最近更新 更多