本地 IDisposable 上缺少 Dispose 调用¶
ID: cs/local-not-disposed
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- efficiency
- maintainability
- external/cwe/cwe-404
- external/cwe/cwe-459
- external/cwe/cwe-460
Query suites:
- csharp-security-and-quality.qls
类型实现 IDisposable 的对象应通过调用 Dispose 进行释放。
建议¶
如果可能,请在 using 块中包装对象的分配,以便在 using 块完成后自动释放对象。
如果无法做到这一点,请确保在对象上调用 Dispose。通常建议在 finally 块中调用 Dispose,以确保即使抛出异常也能释放对象。
示例¶
在此示例中,创建了 FileStream,但未对其进行释放。
using System;
using System.IO;
class Bad
{
long GetLength(string file)
{
var stream = new FileStream(file, FileMode.Open);
return stream.Length;
}
}
在修改后的示例中,使用了 using 语句来确保正确关闭文件流。
using System;
using System.IO;
class Good
{
long GetLength(string file)
{
using (var stream = new FileStream(file, FileMode.Open))
return stream.Length;
}
}
参考¶
MSDN:IDisposable 接口。
常见缺陷列表:CWE-404。
常见缺陷列表:CWE-459。
常见缺陷列表:CWE-460。