如果 .NET 中的 MemoryStream 未关闭,是否会造成内存泄漏? [英] Is a memory leak created if a MemoryStream in .NET is not closed?

查看:58
本文介绍了如果 .NET 中的 MemoryStream 未关闭,是否会造成内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

MemoryStream foo(){
    MemoryStream ms = new MemoryStream();
    // write stuff to ms
    return ms;
}

void bar(){
    MemoryStream ms2 = foo();
    // do stuff with ms2
    return;
}

我分配的 MemoryStream 以后有没有可能以某种方式无法处理?

Is there any chance that the MemoryStream that I've allocated will somehow fail to be disposed of later?

我有一个同行评审坚持要求我手动关闭它,但我找不到信息来判断他是否有一个有效的观点.

I've got a peer review insisting that I manually close this, and I can't find the information to tell if he has a valid point or not.

推荐答案

如果某物是一次性的,您应该始终将其丢弃.您应该在 bar() 方法中使用 using 语句以确保 ms2 被处理.

If something is Disposable, you should always Dispose it. You should be using a using statement in your bar() method to make sure ms2 gets Disposed.

它最终会被垃圾收集器清理干净,但调用 Dispose 总是一个好习惯.如果您在代码上运行 FxCop,它会将其标记为警告.

It will eventually get cleaned up by the garbage collector, but it is always good practice to call Dispose. If you run FxCop on your code, it would flag it as a warning.

这篇关于如果 .NET 中的 MemoryStream 未关闭,是否会造成内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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