0

我在 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
                        {

                        }
            }  
4

1 回答 1

4

这是我几周前从该方法的文档FindAll中学到的东西:

由于实现限制,SearchResultCollection 类在垃圾回收时无法释放其所有非托管资源。为防止内存泄漏,您必须在不再需要 SearchResultCollection 对象时调用 Dispose 方法。

您在using上使用DirectorySearcher,但不在结果集合上使用。尝试将生成的集合分配给以后可以释放的变量:

using (var results = mySearcher.FindAll())
{
    foreach (SearchResult result in results)
    {
        ...
    }
}
于 2018-05-02T19:09:53.487 回答