释放文件句柄。从BitmapImage获取ImageSource。

29

我该如何释放此文件的句柄?

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

这三行代码是什么意思: img.Source = imageSrc; //Do Work imageSrc = null; img.Source = null; - Furkan Gözükara
@MonsterMMORPG 不用担心它们... bitmap.CacheOption = BitmapCacheOption.OnLoad; 是关键部分。 - NitroxDM
2个回答

36

在 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时,源文件将会立即关闭。

见MSDN社区论坛


如果我使用这段代码,应用程序的内存会增加吗? - Ankur Tripathi

1

在处理一个特别棘手的图像时,我一直遇到问题。被接受的答案对我没有用。

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

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

这导致文件句柄被释放。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接