Disposing during foreach(在 foreach 期间处理)
问题描述
在这个问题中:遍历 DirectoryEntry 或任何对象层次结构 - C#
遍历 LDAP 树的建议答案是
The suggested answer for traversing an LDAP tree is to
DirectoryEntry root = new DirectoryEntry(someDN);
DoSomething(root);
function DoSomething(DirectoryEntry de){
// Do some work here against the directory entry
if (de.Children != null) {
foreach (DirectoryEntry child in de.Children) {
DoSomething(child);
}
}
}
我的问题是:你需要在每次迭代结束时对每个孩子调用 Dispose() 吗?或者 foreach 循环会处理对 Dispose() 的必要调用吗?或者它们在 foreach 循环中根本就没有必要(因为也许循环会重复使用其他人想要 Dispose() 的资源)
My Question is: Do you need to call Dispose() on each child at the end of each iteration? or will the foreach-loop handle the necessary calls to Dispose()? or are they simply not necessary in a foreach-loop (because perhaps the loop re-uses the resources one would otherwise want to Dispose())
推荐答案
是的,您需要对每个孩子调用 Dispose.当您调用 DirectoryEntry 的 Children 属性时,它实际上会创建新的 DirectoryEntries 实例.当您枚举该实例时,它会一一拉取子条目(不是一次全部提取),并且不会 Dispose 它们(也不会重用它们).由于 DirectoryEntry 基本上是 COM 对象 - 处理它非常重要(它持有非托管资源).所以正确的方法是这样的:
Yes you need to call Dispose on every child. When you call Children property of DirectoryEntry, it actually creates new DirectoryEntries instance. When you enumerate over that instance, it pulls child entries one by one (not all of them at once), and it will not Dispose them (nor anything will reuse them). Since DirectoryEntry is basically COM object - it's quite important to dispose it (it hold unmanaged resources). So correct way is something like this:
function DoSomething(DirectoryEntry de){
// Do some work here against the directory entry
if (de.Children != null) {
foreach (DirectoryEntry child in de.Children) {
using (child) {
DoSomething(child);
}
}
}
}
这篇关于在 foreach 期间处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 foreach 期间处理
基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
