我在 using 语句中使用 DirectorySearcher 来遍历大约 5000 个对象。通过故障排除,PropertiesToLoad 属性似乎导致大量内存泄漏。如果我在每个对象上设置 propertiesToLoad 属性,我的程序会立即使用 0 GB 到 2 GB 的内存。以这种方式搜索非常快,但存在内存泄漏。
如果我在开始时而不是在每个循环上设置 PropertiesToLoad,则不会发生内存泄漏,但搜索速度很慢。我尝试清除每个循环上的属性,这修复了内存泄漏,但再次导致搜索速度变慢。我希望在这里找到两全其美的东西。
注意:我的应用程序是多线程的,因此 AD 搜索同时发生在 10 个线程上。
using (DirectorySearcher mySearcher = new DirectorySearcher(new DirectoryEntry("LDAP://rootDSE", null, null, AuthenticationTypes.FastBind)))
{
try
{
mySearcher.Filter = ("(&(objectClass=user)(sAMAccountName=" + object + "))");
mySearcher.SearchScope = SearchScope.Subtree;
mySearcher.CacheResults = false;
mySearcher.PropertiesToLoad.AddRange(new string[] { "canonicalName", "displayName", "userAccountControl" });
foreach (SearchResult result in mySearcher.FindAll())
{
try
{
shareInfo.displayname = result.Properties["displayName"][0].ToString();
}
catch
{
shareInfo.displayname = "N/A";
}
shareInfo.canName = result.Properties["canonicalName"][0].ToString();
int userAccountControl = Convert.ToInt32(result.Properties["userAccountControl"][0]);
bool disabled = ((userAccountControl & 2) > 0);
if (disabled == true)
shareInfo.acctstatus = "Disabled";
else
shareInfo.acctstatus = "Enabled";
}
}
catch
{
}
}