我遇到过这样的例程:
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 的范围之外保留对变量的任何引用,这无论如何都会导致问题。
关于c# - 返回具有非处置内存流的对象会导致内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4602825/