zl程序教程

您现在的位置是:首页 >  硬件

当前栏目

基于.NETBitmapImage内存释放问题的解决方法详解

内存方法 问题 详解 解决 基于 释放
2023-06-13 09:14:53 时间

网上查到的代码,多数的写法使用MemoryStream来实现:

复制代码代码如下:

newThread(newThreadStart(()=>{
   varbitmap=newBitmapImage();
   bitmap.BeginInit();

   using(varstream=newMemoryStream(File.ReadAllBytes(...))){
       bitmap.StreamSource=stream;
       bitmap.CacheOption=BitmapCacheOption.OnLoad;
       bitmap.EndInit();
       bitmap.Freeze();

   }
   this.Dispatcher.Invoke((Action)delegate{
       Image1.Source=bitmap;

   });

})).Start();


今天问题来了,当我设置了DecodeWidth为100时加载1000张图片,照理说内存应该维持100×100的1000张图片,但事实上他保留了所以原始图片的内存直到BitmapImage被回收时才释放,这让我很尴尬,换句话说using(MemoryStream)并没有真正按我们预期释放MemoryStream中的Buffer,那如何才能释放呢?
其实最简单就是直接弃用MemoryStream转投FileStream,如下:
复制代码代码如下:

using(varstream=newFileStream(path,FileMode.Open)){
   image.BeginInit();
   image.StreamSource=stream;

   image.DecodePixelWidth=100;

   image.CacheOption=BitmapCacheOption.OnLoad;
   image.EndInit();
   image.Freeze();
}