找不到MSDN文档中的任何这一点。
Can't find anything in the MSDN documentation on this.
即。是它足够的做,说:
I.e. is it enough to do, say:
using(PrincipalSearcher searcher = ...)
{
foreach (var principal in searcher.FindAll())
{
... do something ...
} // The PrincipalSearchResult<T> returned by searcher.FindAll is disposed here
}
这是我见过做最例子,或者我应该做的:
which is what most examples I've seen do, or should I do:
using(PrincipalSearcher searcher = ...)
{
foreach(var principal in searcher.FindAll())
{
using (principal)
{
// ... do something ...
}
}
}
后者(显式地处理迭代中的每个项目)看起来更安全 - 即符合指引,明确处理所有IDisposable的对象 - 但它是一个有点乱;例如,precludes使用LINQ的迭代搜索结果。
The latter (explicitly disposing each item during iteration) looks "safer" - i.e. conforms to the guideline to explicitly dispose all IDisposable objects - but it's a bit messy; for example, it precludes the use of LINQ to iterate over search results.
在回应@ RUP的评论:
In response to @Rup's comment:
您可以编写返回一个结果从父迭代器
you could write a yield iterator that returned one result from the parent iterator
是的,我认为这工作,使LINQ。类似下面的扩展方法:
Yes, I think that would work to enable LINQ. Something like the following extension method:
public static IEnumerable<T> EnumerateAndDispose<T>(this IEnumerable<T> collection) where T : IDisposable
{
foreach (T item in collection)
{
using (item)
{
yield return item;
}
}
}
可以使用的为:
which can be used as:
searcher.FindAll().EnumerateAndDispose().Select(... use LINQ ...)
不过,有必要吗?
But is it necessary?
一般speacking,在很多情况下,不调用Dispose()不会造成大问题:写得好处置的对象将实施清理东西的必要了同样的逻辑终结。 (免责声明:我不是说不叫处理:!这是有原因的。例如,最终确定可能发生了很多后来我只说明什么后果这里)
Generally speacking, in many cases, not calling Dispose() will not cause big problems: well written disposable objects will implement the same logic needed to clean things up in the finalizer. (Disclaimer: I'm not saying "do not call dispose": it is there for a reason! For example, Finalization can happen a lot later. I'm only describing what are the consequences here).
不过,AD对象是一个明显的例外;尤其是, SearchResultCollection
是众所周知的,从这个问题的痛苦(参考:MSDN(既类文档及其他物品),和Active目录:设计,部署和运行Active Directory )。看来,由于技术原因,不可能以释放资源在其终结,所以不调用dispose将导致内存泄漏。
However, AD objects are a notable exception; in particular, SearchResultCollection
is known for suffering from this problem (references: MSDN (both the class docs and other articles), and Active Directory: Designing, Deploying, and Running Active Directory). It seems that for technical reasons it is not possible to release resources in its finalizer, so not calling dispose will lead to memory leaks.
正如斯科特和乔,很多MSDN的例子并不调用Dispose集合中的物品;然而,瑞安邓恩,前Windows Azure的技术专家与人合着的的.NET开发人员指南目录服务编程的,建议使用来调用的