在 foreach 期间处理

Disposing during foreach(在 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.当您调用 DirectoryEntryChildren 属性时,它实际上会创建新的 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 期间处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

What#39;s the difference between retrieving WindowsPrincipal from WindowsIdentity and Thread.CurrentPrincipal?(从 WindowsIdentity 和 Thread.CurrentPrincipal 检索 WindowsPrincipal 之间有什么区别?)
How do I find a user#39;s Active Directory display name in a C# web application?(如何在 C# Web 应用程序中查找用户的 Active Directory 显示名称?)
How can I authenticate against Active Directory in Nancy?(如何在 Nancy 中对 Active Directory 进行身份验证?)
How to get a username in Active Directory from a display name in C#?(如何从 C# 中的显示名称获取 Active Directory 中的用户名?)
Working with DirectoryServices in ASP.NET Core(在 ASP.NET Core 中使用 DirectoryServices)
Create Active Directory user in .NET (C#)(在 .NET (C#) 中创建 Active Directory 用户)