我正在使用 C# 中的 ManagementObjects 和 foreach 循环。Coverity 声称这样的代码存在泄漏:
ObjectQuery myQuery = new ObjectQuery("Select * from Win32_Printer");
using (ManagementObjectSearcher mySearcher = new ManagementObjectSearcher(myQuery))
{
// alloc_fn: A new resource is returned from allocation method Current.get
// var_assign: Assigning: mo = resource returned from mo$iterator.Current
foreach (ManagementObject mo in mySearcher.Get())
{
foreach (PropertyData p in mo.Properties)
{
// do stuff, maybe return a string
}
}
}
// leaked_resource: Returning without closing mo leaks the resource that it refers to
return "";
这是真正的泄漏还是误报?
这里甚至需要 using 块(这是我最初避免泄漏的尝试)?
我的想法是,这是一个实现 IDisposable 的托管集合,调用者不应该负责销毁它。我之前看过以下建议的代码,但似乎它正在使用更多 using 块走错路:
...
foreach (ManagementObject mo in mySearcher.Get()) using(mo)
...