is DirectorySearcher.SizeLimit = 1 for FindAll() equal to FindOne() [DirectoryServices/.net]

醉酒当歌 提交于 2019-12-14 03:55:36

问题


When using the DirectorySearcher in .net, are these two statements equal?

Same for both:

Dim ds As New DirectorySearcher
' code to setup the searcher

First statement

ds.FindOne()

Second statement

ds.SizeLimit = 1
ds.FindAll()

...except obviously that FindOne() returns a SearchResult object and FindAll() returns a SearchResultCollection object


回答1:


Yes, that would be almost the same.

Almost, because in .NET 2.0 (not sure if it's been fixed in more recent versions), the .FindOne() call had some issues with leaking memory, so best practice is (or was) to always use .FindAll() and iterate over your results.

Marc




回答2:


@marc_s is right, except that the FindOne memory leak bug was in .NET 1.x and is fixed in .NET 2.0.

It happened because the .NET 1.x implementation of FindOne calls FindAll under the covers and does not always dispose the SearchResultCollection returned by FindAll:

public SearchResult FindOne()
{
    SearchResultCollection collection1 = this.FindAll(false);
    foreach (SearchResult result1 in collection1)
    {
       collection1.Dispose();
       return result1;
    }
    return null;
}

In the above code collection1.Dispose will not be called if the collection is empty (no result is found), resulting in a memory leak as described in the remarks section of the MSDN documentation for FindAll.

You can use FindOne safely in .NET 2.0. Or if you use FindAll, you need to make sure you dispose the returned SearchResultCollection or you will have the same memory leak, e.g.:

public SearchResult MyFindOne()
{
    using(SearchResultCollection results = this.FindAll(false))
    {
        if(results.Count > 0) return results[0];
        return null;
    }
}


来源:https://stackoverflow.com/questions/1135013/is-directorysearcher-sizelimit-1-for-findall-equal-to-findone-directoryse

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