public async Task<UserInfo> GetUserDataAsync(string NetworkID)
{
PrincipalContext principalcontext = new PrincipalContext(ContextType.Domain, ADDomain, ADUser, ADPass);
UserPrincipal founduser = null;
await Task.Run(() =>
{
founduser = UserPrincipal.FindByIdentity(principalcontext, IdentityType.SamAccountName, NetworkID);
});
//task.Wait();
return founduser != null && founduser.Enabled == true ?
new UserInfo
{
DisplayName = founduser.DisplayName,
Email = founduser.EmailAddress,
NetworkID = founduser.SamAccountName
} : new UserInfo();
}
这是一个假设通过广告验证用户的函数,我可以使用 Task task = Task.Factory.StartNew (() => {}) 运行该函数;和任务。等待();但这仍然会同步运行该功能。使用 async 和 await 运行上面的代码会使浏览器陷入死锁,永远旋转并且永远不会返回值。
最佳答案
如果您想异步执行此操作,为什么不直接返回任务呢?
public Task<UserInfo> GetUserDataAsync(string NetworkID)
{
return Task.Run(() =>
{
PrincipalContext principalcontext = new PrincipalContext(ContextType.Domain, ADDomain, ADUser, ADPass);
UserPrincipal = UserPrincipal.FindByIdentity(principalcontext, IdentityType.SamAccountName, NetworkID);
return founduser != null && founduser.Enabled == true ?
new UserInfo
{
DisplayName = founduser.DisplayName,
Email = founduser.EmailAddress,
NetworkID = founduser.SamAccountName
} : new UserInfo();
});
}
关于c# - async Task<object> 函数死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26364334/