为什么我得到一个内存不足的错误,当我使用使用? [英] Why do I get the an out of memory error when I use using?

查看:117
本文介绍了为什么我得到一个内存不足的错误,当我使用使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的方法,来转换一个的BitmapImage System.Drawing.Bitmap

I have the following method, to convert a BitmapImage to a System.Drawing.Bitmap:

public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
    Bitmap bitmap;

    using (var ms = new MemoryStream())
    {
        var encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
        encoder.Save(ms);

        bitmap = new Bitmap(ms);
    }

    return bitmap;
}



每当我尝试使用返回的位图对象,我得到以下错误:

Whenever I try and use the returned Bitmap object, I get the following error:

OutOfMemoryException异常发生 - 内存不足。

OutOfMemoryException occured - Out of memory.

然而,每当我用这个替换代码:

However, whenever I replace the code with this:

public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
    var ms = new MemoryStream();

    var encoder = new JpegBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bitmapImage));

    encoder.Save(ms);

    return new Bitmap(ms);
}

这工作正常。不过,我敢肯定,我应该使用使用作为的MemoryStream 对象实现的IDisposable 。这是怎么回事呢?

This works fine. However, I am pretty sure that I am supposed to use using as the MemoryStream object implements IDisposable. What's going on here?

推荐答案

位图的构造的Bitmap构造函数(流)声称

您必须保持流开放寿命的位图。

You must keep the stream open for the lifetime of the Bitmap.

在你的情况,当你使用使用声明中,流(即一次性)自动处理,所以你的位图对象变为无效。这不是您分配了太多的内存,但有关该位点-something不再存在。

In your case, when you're using using statement, stream (being Disposable) automatically disposed, so your Bitmap object becomes invalid. It's not about that you allocate too much memory, but about that bitmap point to -something that no longer exists.

这篇关于为什么我得到一个内存不足的错误,当我使用使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆