静态分析工具一直告诉我,我的 C# 代码中存在资源泄漏。
这是一个例子:
StringReader reader = new StringReader(...);
// do something with reader
...
} // static analysis tool cries that I've leaked **reader**
我的工具正确吗?如果是,为什么?
编辑(回复评论)- 我的静态分析工具说我有一堆资源泄漏。我从这个知道forum某些 Java AWT 对象需要显式释放,否则会发生泄漏。是否有需要显式释放的 C# 对象?
最佳答案
是的,您的代码泄漏严重。应该是这样的:
using (StringReader reader = new StringReader(...))
{
}
每个实现 IDisposable
的类都需要包装在 using block 中以确保始终调用 Dispose
方法。
更新:
详述:在 .NET 中有 IDisposable定义 Dispose 方法的接口(interface)。实现此接口(interface)的类(如文件流、数据库连接、读取器等)可能包含指向非托管资源的指针,确保释放这些非托管资源/句柄的唯一方法是调用 Dispose 方法。因此在 .NET 中,即使抛出异常也能确保调用某些代码是使用 try/finally 语句:
var myRes = new MyResource(); // where MyResource implements IDisposable
try
{
myRes.DoSomething(); // this might throw an exception
}
finally
{
if (myRes != null)
{
((IDisposable)myRes).Dispose();
}
}
编写 C# 代码的人很快意识到,每次处理一次性资源时都编写此代码是一种 PITA。所以他们引入了 using
语句:
using (var myRes = new MyResource())
{
myRes.DoSomething(); // this might throw an exception
}
有点短。
关于c# - 垃圾收集器不清理哪些对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4261041/