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 期间处理
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 使用 rss + c# 2022-01-01
