释放文件句柄.BitmapImage中的ImageSource

Nit*_*xDM 25 c# wpf xaml

如何释放此文件的句柄?

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.
}
Run Code Online (Sandbox Code Playgroud)


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;
}
Run Code Online (Sandbox Code Playgroud)

cst*_*ler 30

在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;
}
Run Code Online (Sandbox Code Playgroud)

当您使用上述方法获得ImageSource时,源文件将立即关闭.

看MSDN社交论坛