欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-01 14:52:04
网上查到的代码,多数的写法使用memorystream来实现:复制代码 代码如下:new thread(new threadstart(() => { &n...

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

复制代码 代码如下:

new thread(new threadstart(() => {
    var bitmap = new bitmapimage();
    bitmap.begininit();

    using (var stream = new memorystream(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 (var stream = new filestream(path, filemode.open)) {
    image.begininit();
    image.streamsource = stream;

    image.decodepixelwidth = 100;

    image.cacheoption = bitmapcacheoption.onload;
    image.endinit();
    image.freeze();
}