I'm using .net 4.7.2 (not core) and C#.
I need to come up with a way to to not block my current async tasks and I have a need to search for a user as part of these tasks. I've done DirectorySearcher operations previously so I know the attachment to AD and first search can take a few seconds which will really throw a wrench in the gears if I try calling it from my existing async methods.
I found that the DirectorySearcher has an "Asynchronous" property. But I don't think it does the async pattern.
DirectorySearcher ds = new DirectorySearcher();
ds.Asynchronous = true;
ds.Filter = "(&(objectclass=user)(samaccountname=testaccount)";
ds.PropertiesToLoad.Add("samaccountname");
SearchResult sr = await ds.FindOne();
Of course, the last line throws an error because FindOne is not an async method. I already know that if I remove the await it will compile. But that doesn't solve my problem with calling this from existing awaited methods. I need to find a way to do an async search in AD...
Does anyone know how I could get this to work in the .net framework (not core)?
Try running it on the thread pool.
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();
});
}
For reference: https://docs.microsoft.com/dotnet/api/system.threading.tasks.task.run
None of MS products do this....
I did find an active nuget project called ldap4net which does.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.