问题
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