如何在MVC中执行await方法 参考Async/Await - Best Practices in Asynchronous Programming

我们正在使用microsoft Graph SDK。在控制台应用程序中实现了POC,该代码可以正常工作,但是在MVC中添加此代码后,它无法正常工作。代码卡在等待调用中

的身份从控制器中调用
 [HttpPost]
    public actionResult InviteUser([Bind(Include = "EmailId")] UserLogin userLogin)
    {
        if (ModelState.IsValid)
        {
            string result = AzureADUtil.InviteUser(userLogin.EmailId);
        }
        return View();
    }

方法实现如下

  public static string InviteUser(string emailaddress)
    {
        string result = string.Empty;

        result = InviteNewUser(emailaddress).Result;

        return result;

    }

    private static async Task<string> InviteNewUser(string emailaddress)
    {
        string result = string.Empty;
        try
        {
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
            .Create(clientId)
            .WithTenantId(tenantID)
            .WithClientSecret(clientSecret)
            .Build();

            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            GraphServiceclient graphClient = new GraphServiceclient(authProvider);

            // Send Invitation to new user
            var invitation = new Invitation
            {
                InvitedUserEmailaddress = emailaddress,InviteRedirectUrl = "https://myapp.com",SendInvitationmessage = true,InvitedUserType = "Member" 

            };

            // It stucks at this line
            await graphClient.Invitations
            .Request()
            .AddAsync(invitation);

        }
        catch (Exception ex)
        {
            result = ex.Message;
        }
        return result;

    }
yjyhp5211314 回答:如何在MVC中执行await方法 参考Async/Await - Best Practices in Asynchronous Programming

混合异步等待和阻塞代码.Result.Wait()往往会导致死锁,尤其是在asp.net-mvc上。

如果要异步,请一直进行下去。

[HttpPost]
public async Task<ActionResult> InviteUser([Bind(Include = "EmailId")] UserLogin userLogin) {
    if (ModelState.IsValid) {
        string result = await AzureADUtil.InviteUser(userLogin.EmailId);
    }
    return View();
}

实现也重构为异步

public static async Task<string> InviteUser(string emailAddress)
{
    string result = string.Empty;

    result = await InviteNewUser(emailAddress);

    return result;
}

InviteUser现在是多余的,因为它基本上包装了专用的InviteNewUser调用。

参考Async/Await - Best Practices in Asynchronous Programming

,

最好是更新代码以在请求链的整个过程中异步运行。您可以按照以下步骤进行操作:

[HttpPost]
public async Task<ActionResult> InviteUser([Bind(Include = "EmailId")] UserLogin userLogin)
{
    if (ModelState.IsValid)
    {
        string result = await AzureADUtil.InviteNewUser(userLogin.EmailId).ConfigureAwait(false);
    }
    return View();
}
本文链接:https://www.f2er.com/3149880.html

大家都在问