Disposing during foreach

你说的曾经没有我的故事 提交于 2019-12-02 03:40:47

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