我试图从Active Directory中读取所有用户。但是,这相当慢(300个用户大约需要10秒)。这是代码:
public void LoadADUsers()
{
using (var Context = new PrincipalContext(ContextType.Domain, "MyServer"))
{
using (var Searcher = new PrincipalSearcher(new UserPrincipal(Context)))
{
var DirectorySearcher = (DirectorySearcher)Searcher.GetUnderlyingSearcher();
DirectorySearcher.PropertiesToLoad.Clear();
DirectorySearcher.PropertiesToLoad.Add("cn");
DirectorySearcher.PropertiesToLoad.Add("samAccountName");
foreach (var Result in Searcher.FindAll())
{
var Entry = (DirectoryEntry)Result.GetUnderlyingObject();
string FullName = (string)Entry.Properties["cn"].Value;
string AccountName = (string)Entry.Properties["samAccountName"].Value;
ADUsers.Add(new ADUser(Entry.Guid.ToString(), FullName, AccountName));
}
}
}
}
现在,Context
对象的创建大约需要7秒,这可能是因为这是建立与服务器的连接的地方。有什么方法可以加快速度吗?
此外,循环大约需要2.5秒,这可能意味着仍然与AD服务器进行通信。我预计Searcher.FindAll()
电话会立即收到所有用户,但事实并非如此。有什么方法可以强制执行该行为,或以其他方式加快循环?
答案 0 :(得分:2)
我不清楚为什么你坚持两次获取底层对象(DirectorySearcher
,然后你甚至根本不使用它,DirectoryEntry
,using (var Context = new PrincipalContext(ContextType.Domain, "MyServer"))
using (var Searcher = new PrincipalSearcher(new UserPrincipal(Context)))
{
foreach(var result in Searcher.FindAll()) // those are 'Principal' objects...
{
// cast to "UserPrincipal"
UserPrincipal up = result as UserPrincipal;
// if successful - use the object properties directly on the 'UserPrincipal'
// absolutely no point and benefit in "downcasting" to a 'DirectoryEntry' !
if (up != null)
{
string FullName = up.DisplayName;
string AccountName = up.SamAccountName;
ADUsers.Add(new ADUser(up.Guid.ToString(), FullName, AccountName));
}
}
}
1}}) - 如果你已经使用了更先进的那个......这也会花费时间!!
我会这样做:
{{1}}