c# - async Task<object> 函数死锁

标签 c# asynchronous async-await

    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/

相关文章:

c# - 如何使用 Windows MediaCapture API 捕获 "Audio Only"?

c# - DateTime 的 StringFormat 不适用于 MultiBinding

javascript - 如何登录异步/等待上下文

winsock中的异步地址解析?

nhibernate - 如何在 Web API 异步任务中保留 HttpContext

c# - Xamarin Async ViewDidAppear 在 ViewDidLoad 期间调用

javascript - await 是 async 函数内部的保留字错误

c# - 将 listview 列从数字格式格式化为 int

c# - 实现自定义角色提供者,不能覆盖 Roles.IsUserInRole(String)

python-3.x - 在 Python 中追加到合并的异步生成器