DirectorySearcher 异步使用 await

DirectorySearcher Asynchronous using await

我正在使用 .net 4.7.2(非核心)和 C#。

我需要想出一种方法来不阻止我当前的异步任务,并且我需要在这些任务中搜索用户。我之前已经完成了 DirectorySearcher 操作,所以我知道 AD 的附件和第一次搜索可能需要几秒钟,如果我尝试从我现有的异步方法调用它,这真的会造成麻烦。

我发现 DirectorySearcher 有一个 "Asynchronous" 属性。但我不认为它执行异步模式。

        DirectorySearcher ds = new DirectorySearcher();
        ds.Asynchronous = true;
        ds.Filter = "(&(objectclass=user)(samaccountname=testaccount)";
        ds.PropertiesToLoad.Add("samaccountname");
        SearchResult sr = await ds.FindOne();

当然,最后一行会抛出错误,因为FindOne 不是异步方法。我已经知道如果我删除 await 它将编译。但这并不能解决我从现有的等待方法中调用它的问题。我需要找到一种在 AD 中进行异步搜索的方法...

有谁知道我如何让它在 .net 框架(非核心)中工作?

在线程池上尝试运行。

private async void MyAsyncMethod()
{
   // do some asynchronous thing
   // await something

   // then, run below on thread pool, which would not block MyAsyncMethod
   Task.Run(() =>
   {
      DirectorySearcher ds = new DirectorySearcher();
      ds.Asynchronous = true;
      ds.Filter = "(&(objectclass=user)(samaccountname=testaccount)";
      ds.PropertiesToLoad.Add("samaccountnamt");
      SearchResult sr = ds.FindOne();
   });
}

供参考: https://docs.microsoft.com/dotnet/api/system.threading.tasks.task.run

None 的 MS 产品这样做....

我确实找到了一个名为 ldap4net 的活跃 nuget 项目。