【问题标题】:System.DirectoryServices.AccountManagement Performance Issue?System.DirectoryServices.AccountManagement 性能问题?
【发布时间】:2010-02-15 02:53:16
【问题描述】:

以下 C# 代码 (.NET Framework 3.5) 返回 AD 组“xyz”的所有用户的名称和描述。只要它返回少量记录,它就可以很好地工作。但是,当它返回超过 100 条记录时,它非常慢。任何建议将不胜感激。提前谢谢!

var context = new PrincipalContext(ContextType.Domain);

var grp = GroupPrincipal.FindByIdentity(context, "xyz");

var users = grp.GetMembers(true);

var usersList = users.Select(n => new { UserName = n.Name, 
                                        Description = n.Description })
                      .OrderBy(o => o.UserName.ToString());

Console.WriteLine(usersList.ToList());

【问题讨论】:

    标签: .net c#-3.0 active-directory asp.net-3.5


    【解决方案1】:

    执行属性范围查询 (ASQ) 会有更好的性能。下面是一些示例代码:

    DirectoryEntry group = new DirectoryEntry("LDAP://CN=All Staff,OU=Groups,DC=domain,DC=local");
    
    DirectorySearcher searcher = new DirectorySearcher();
    searcher.SearchRoot = group;
    searcher.Filter =
       "(&(objectClass=user)(objectCategory=person)(mail=*))";
    searcher.PropertiesToLoad.Add("mail");
    searcher.SearchScope = SearchScope.Base;
    
    searcher.AttributeScopeQuery = "member";
    
    List<string> mail;
    using (SearchResultCollection results = searcher.FindAll())
    {
       mail = new List<string>();
       foreach (SearchResult result in results)
       {
            mail.Add(result.Properties["mail"][0].ToString());
       }
    }
    

    一般而言,System.DirectoryServices.AccountManagement 的性能会比 System.DirectoryServices 慢。然而,99% 的时间你不会注意到它。但是,在这种情况下,您的示例将遍历每个对象并将其拉过网络,而我的示例是利用 LDAP 代表我们完成所有工作。

    请注意,此代码仅适用于成员少于 1000 人的群组。如果你有一个比这更大的组,你需要分页更复杂的代码,但没什么大不了的。

    【讨论】:

    • 非常感谢!当我将 grp.GetMembers(true) 更改为 grp.GetMembers(false) 时,我注意到性能有所提高。我的代码还返回了所有行而不是前 1000 行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 2022-01-04
    • 2010-09-05
    • 2012-09-25
    • 2015-05-28
    • 2015-06-20
    相关资源
    最近更新 更多