返回具有未释放内存流的对象会导致内存泄漏吗?
我遇到过这样的例程:
static public Bitmap byte2bmp(byte[] BitmapData)
{
MemoryStream ms = new MemoryStream(BitmapData);
return (new Bitmap(ms));
}
我担心这可能不是最好的推荐方法。在这种情况下,ms 是否得到正确处理?
或者将结果分配给临时位图,处理流,然后返回临时对象会更好吗?
static public Bitmap byte2bmp(byte[] BitmapData)
{
MemoryStream ms = new MemoryStream(BitmapData);
Bitmap temp=new Bitmap(ms);
ms.Dispose();
return (temp);
}
我希望在这种情况下可以使用“使用”,但不确定它是否会正常工作:
static public Bitmap byte2bmp(byte[] BitmapData)
{
using(MemoryStream ms = new MemoryStream(BitmapData))
{
return (new Bitmap(ms));
}
}
什么是最有效/正确的解决方案?谢谢!
I've come across a routine that does something like this:
static public Bitmap byte2bmp(byte[] BitmapData)
{
MemoryStream ms = new MemoryStream(BitmapData);
return (new Bitmap(ms));
}
I'm worried this might not be the best recommended approach. Does the ms gets disposed properly in this scenario?
Or would it be better to assign the result to a temporary Bitmap, dispose of the stream, and then return the temp object?
static public Bitmap byte2bmp(byte[] BitmapData)
{
MemoryStream ms = new MemoryStream(BitmapData);
Bitmap temp=new Bitmap(ms);
ms.Dispose();
return (temp);
}
I was hoping the "using" might be used in this scenario, but am not sure it would behave properly or not:
static public Bitmap byte2bmp(byte[] BitmapData)
{
using(MemoryStream ms = new MemoryStream(BitmapData))
{
return (new Bitmap(ms));
}
}
What is the most effective/proper solution? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您担心第一种方法无法处理
ms
是正确的。作为良好实践,您应该始终对实现IDisposable
的对象调用Dispose
方法。我建议采用最后一种方法。您可以确信
using
语句将按预期处理该对象,即使您在其中返回也是如此。以下是代码在运行时的分解方式:首先,将评估 return 表达式,然后评估 try-finally 块(其中
using
语句只是语法糖)将被执行,最后该方法将返回。在
using
语句中间返回时可能遇到问题的唯一情况是 如果您从using
语句本身返回变量。当然,如果您在using
块的范围之外保留对变量的任何引用,无论如何这都会导致问题。另请参阅:有关从 using 块返回的最佳实践
You're correct in worrying that the first approach will fail to dipose
ms
. As a matter of good practice, you should always call theDispose
method on objects that implementIDisposable
.I recommend adopting the last approach. You can be confident that a
using
statement will dispose of the object as expected even if you return in the middle of it.Here's how the code would break down during run time: First, the return expression will be evaluated, then the try-finally block (for which the
using
statement is simply syntactic sugar) will be executed, and finally the method will return.The only case in which you might encounter issues with returning in the middle of a
using
statement is if you return the variable from theusing
statement itself. Of course, this would cause issues anyway if you retained any reference to the variable beyond the scope of theusing
block.Also see: Best practice regarding returning from using blocks