WPF的BitmapImage的文件無法釋放及內存泄露的問題


相信用過WPF的BitmapImage的,都在用類似這樣的代碼來解決文件無法刪除的問題!

如果看看msdn上簡單的描述,可以看到這樣的說明:


如果 StreamSource 和 UriSource 均設置,則忽略 StreamSource 值。

如果要在創建 BitmapImage 后關閉流,請將 CacheOption 屬性設置為 BitmapCacheOption.OnLoad。 默認 OnDemand 緩存選項保留對流的訪問,直至需要位圖並且垃圾回收器執行清理為止。

 

 

 

static class AppHelper
{
public static BitmapImage GetBitmapImage(string path)
{
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();

 

image.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = new MemoryStream(File.ReadAllBytes(path));
bitmap.EndInit();
bitmap.Freeze();
return bitmap;
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM