c# - 返回具有非处置内存流的对象会导致内存泄漏?

标签 c# dispose using

我遇到过这样的例程:

static public Bitmap byte2bmp(byte[] BitmapData)
{
    MemoryStream ms = new MemoryStream(BitmapData);
    return (new Bitmap(ms));
}

我担心这可能不是最佳推荐方法。在这种情况下,MS 是否得到妥善处置?

或者将结果分配给临时 Bitmap,处理流,然后返回临时对象会更好吗?

static public Bitmap byte2bmp(byte[] BitmapData)
{
    MemoryStream ms = new MemoryStream(BitmapData);
    Bitmap temp=new Bitmap(ms);
    ms.Dispose();
    return (temp);
}

我希望在这种情况下可以使用“using”,但我不确定它是否会正常运行:

static public Bitmap byte2bmp(byte[] BitmapData)
{
    using(MemoryStream ms = new MemoryStream(BitmapData))
    {
    return (new Bitmap(ms));
    }
}

什么是最有效/最合适的解决方案?谢谢!

最佳答案

您担心第一种方法无法处理 ms,这是正确的。作为一种良好做法,您应该始终对实现 IDisposable 的对象调用 Dispose 方法。

我建议采用最后一种方法。您可以确信 using 语句会按预期处理对象,即使您在其中返回。

以下是代码在运行时的分解方式:首先,返回表达式将被求值,然后 try-finally block (using statement 只是语法糖)将被执行,最后方法将返回。

您可能会遇到在 using 语句中间返回问题的唯一情况是 if you return the variable from the using statement itself .当然,如果您在 using block 的范围之外保留对变量的任何引用,这无论如何都会导致问题。

另见:Best practice regarding returning from using blocks

关于c# - 返回具有非处置内存流的对象会导致内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4602825/

相关文章:

特定类的 C# AttributeUsage

.net - 为什么即使我不调用服务的 Dispose() 方法也会调用它? (使用 BasicHttpBinding)

c# - 我的代码是否正确清理了它的 List<MemoryStream>?

julia - IJulia 因预编译 LoadError 而失败

c++ - 与可变参数模板一起使用

c# - 如何创建 Azure.AsyncPageable 进行模拟?

c# - 等效于 Java 中的 C# 关键字 'as'

c# - HH :MM:SS format getting converted to days instead of hours

c# - 如何访问我在该 block 外的 using block 中填充的变量?

c# - 在 Entity Framework 中使用 'using' 语句的正确方法