我需要在多个路径上查询LDAP,并且我希望出于各种原因使用DirectoryServices。
var ADobjects = new Dictionary<string, ADobject>();
foreach (var OUItem in OUs)
{
using (DirectoryEntry ldap = new DirectoryEntry("LDAP://" + OUItem))
{
using (DirectorySearcher searcher = new DirectorySearcher(ldap))
{
searcher.Filter = "(objectClass=user)";
searcher.PropertiesToLoad.Add("distinguishedName");
searcher.PropertiesToLoad.Add("cn");
searcher.PropertiesToLoad.Add("displayName");
using (SearchResultCollection results = searcher.FindAll())
{
foreach (SearchResult result in results)
{
var dn = result.Properties["distinguishedName"][0].ToString();
if (!ADobjects.ContainsKey(dn))
{
ADobjects.Add(dn, new ADobject(result));
}
}
}
}
}
}
这可行..但是当我有10个OU要查询时,我想并行启动这些查询。
我知道如何启动异步方法(或多或少)但是如何使用这些查询同时填充1个字典?
我点击了一下,但我真的不确定这是否可以而且应该是异步的。由于每次搜索可能需要几秒钟,因此可以从异步任务中获益。
答案 0 :(得分:0)
您可以使用期货http://msdn.microsoft.com/en-us/library/ff963556.aspx
来自上述来源的例子:
int BufferSize = ...
var buffer1 = new BlockingCollection<string>(BufferSize);
var f = new TaskFactory(TaskCreationOptions.LongRunning,
TaskContinuationOptions.None);
var stage1 = f.StartNew(() => LdapSearch(buffer1));
var stage2 = f.StartNew(() => LdapSearch(buffer1));
var stage3 = f.StartNew(() => LdapSearch(buffer1));
var stage4 = f.StartNew(() => LdapSearch(buffer1));
Task.WaitAll(stage1, stage2, stage3, stage4);
static void LdapSearch(BlockingCollection<string> output,
)
{
output.Add(some result);
}