使用 C# 目录服务连接到 LDAP 时正确处置资源
在我看来,在调用目录服务 API 时,应该始终正确地处置资源,无一例外(但许多示例、博客和教程经常忽略,或者以一种方式处理此调用,而以另一种方式处理另一个调用)。由于以下所有 DS 类都实现了 Dispose 方法,因此我只想一劳永逸地确认:
using (DirectoryEntry dirEntry = new DirectoryEntry())
{
using (DirectorySearcher dirSearcher = new DirectorySearcher())
{
dirSearcher.SearchRoot = dirEntry;
dirSearcher.Filter = ...;
using (SearchResultCollection src = dirSearcher.FindAll())
{
//Other code that deals with result
}
}
}
应该始终完成。我总是系统而虔诚地执行上述操作是否会遇到任何风险?
It seems to me that one should always properly dispose resources when calling Directory Services API with no exception (yet many samples, blogs and tutorials often ignore, or do one way with this call, and the other way with another call). Since all of the following DS classes implement the Dispose method, so I just want to confirm once and for all:
using (DirectoryEntry dirEntry = new DirectoryEntry())
{
using (DirectorySearcher dirSearcher = new DirectorySearcher())
{
dirSearcher.SearchRoot = dirEntry;
dirSearcher.Filter = ...;
using (SearchResultCollection src = dirSearcher.FindAll())
{
//Other code that deals with result
}
}
}
should always be done. Am I running into any risk by always systematically and religiously doing the above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
处置目录服务对象实际上非常重要 - 其中许多对象包装 COM+ 资源,如果处置失败,将导致资源泄漏。
所以,是的,您确实在做正确的事情,并且不,当您将它们包装在
using
中时,没有风险。It's actually very important to dispose Directory Services objects - many of them wrap COM+ resources and you will cause resource leaks if you fail to dispose.
So yes, you're doing the right thing, definitely, and no, there's no risk when you wrap them in
using
.