Disposing during foreach

£可爱£侵袭症+ 提交于 2019-12-02 01:52:35

问题


In this question: Looping through DirectoryEntry or any object hierarchy - C#

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);
        }
    }
}

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())


回答1:


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);
            }
        }
    }
}


来源:https://stackoverflow.com/questions/41378746/disposing-during-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!