async Task <object> function deadlock </object>

时间:2014-10-14 15:15:28

标签: 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(()=&gt; {})运行该功能;和task.Wait();但那仍然会同步运行该功能。使用async和await运行上面的代码会使浏览器陷入死锁,这种死锁会永远旋转,永远不会返回值。

2 个答案:

答案 0 :(得分:1)

如果您想异步执行此操作,为什么不直接返回任务?

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();
    });
}

答案 1 :(得分:-1)

这就是我最后用同步电话做的事情。

Task task = Task.Factory.StartNew(() =>
            {
                founduser = UserPrincipal.FindByIdentity(principalcontext,IdentityType.SamAccountName, NetworkID);
            });

            task.Wait();