从非异步方法运行异步代码

时间:2016-08-17 20:28:47

标签: c# asynchronous async-await

我正在尝试从Azure AD获取访问令牌,异步调用永远不会完成。我不确定我做错了什么,也许有人可以指出我正确的方向。这是代码:

private static void GetAccessTokenNonAsync()
    {
        Func<System.Threading.Tasks.Task> task = async () => { await GetAccessToken().ConfigureAwait(false); };
        task().Wait();
    }
    private static async Task<AuthenticationResult> GetAccessToken()
    {
        string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
        string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
        string source = ConfigurationManager.AppSettings["ExchangeOnlineId"];

        var authContext = new AuthenticationContext(aadInstance, false);
        var credentials = new ClientCredential(clientId, clientSecret);
        var appRedirectUrl = HttpContext.Current.GetOwinContext().Request.Scheme + "://" + HttpContext.Current.GetOwinContext().Request.Host + HttpContext.Current.GetOwinContext().Request.PathBase + "/";
        var res =
             await
                 authContext.AcquireTokenByAuthorizationCodeAsync(
                     ((ClaimsIdentity)HttpContext.Current.User.Identity).FindFirst("AuthenticationCode").Value,
                     new Uri(appRedirectUrl), credentials, source).ConfigureAwait(false);
        Current.AccessToken = res.AccessToken;
        return res;

    }
    private static string AccessToken
    {
        get
        {
            return HttpContext.Current.Session["AccessToken"].ToString();
        }
        set { HttpContext.Current.Session["AccessToken"] = value; }
    }

在我的main方法中,我调用了GetAccessTokenNonAsync()

4 个答案:

答案 0 :(得分:3)

您正在遇到deadlock scenario because you're blocking on async code。我在博客上描述了详细信息。

理想情况下,您不应该在任何新代码中使用HttpContext.Current。在相当长的一段时间内,它被认为是糟糕的做法,并且已经在ASP.NET Core中完全删除了(并且没有回来)。

看起来您想要做的是将令牌存储在会话状态中,并且(异步地)在必要时创建它。执行此操作的适当方法是使访问器异步:

public static async Task<string> GetAccessTokenAsync()
{
  var result = HttpContext.Current.Session["AccessToken"] as string;
  if (result != null)
    return result;

  ...

  var res = await authContext.AcquireTokenByAuthorizationCodeAsync(...);
  result = res.AccessToken.ToString();
  HttpContext.Current.Session["AccessToken"] = result;
  return result;
}

答案 1 :(得分:1)

您未正确使用async关键字。这样的事情应该有效:

public static void GetAccessTokenNonAsync()
{
    // Call the async method and get the resulting task.
    Task<AuthenticationResult> accessTokenTask = GetAccessToken();
    // Wait for the task to finish.
    accessTokenTask.Wait();
}

private async static Task<AuthenticationResult> GetAccessToken()
{
    return await Task.Factory.StartNew<AuthenticationResult>
    (
        () =>
        {
            // Insert code here.
            return new AuthenticationResult();
        }
    );
}

答案 2 :(得分:1)

最终有效的代码是:

 private static void GetAccessTokenNonAsync()
    {
        var userId = ((ClaimsIdentity)HttpContext.Current.User.Identity).FindFirst("UserId").Value;

        var task = System.Threading.Tasks.Task.Run(async () =>
        {
            return await GetAccessToken( userId);
        });
        task.Wait();
        Current.AccessToken = task.Result.AccessToken;
        Current.AccessTokenExpiresOn = task.Result.ExpiresOn.ToString();
    }

    private static async Task<AuthenticationResult> GetAccessToken(string userId)
    {

        return await System.Threading.Tasks.Task.Factory.StartNew<AuthenticationResult>
        (
            () =>
            {
                string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
                string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
                string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
                string source = ConfigurationManager.AppSettings["ExchangeOnlineId"];

                var authContext = new AuthenticationContext(aadInstance, false);
                var credentials = new ClientCredential(clientId, clientSecret);
                var res =
                    authContext.AcquireTokenSilentAsync(source, credentials,
                        new UserIdentifier(userId, UserIdentifierType.UniqueId)).Result;
                return res;
            }
        );
    }

答案 3 :(得分:0)

由于异步代码返回某些内容(使用任务签名),如果您定位最新的.net框架,请尝试执行此操作:

private static void GetAccessTokenNonAsync()
{
    var result = GetAccessToken().ConfigureAwait(false).Result;
}