从MVC控制器调用方法挂起由于异步等待 [英] Calling method from MVC controller hangs due to async await

查看:434
本文介绍了从MVC控制器调用方法挂起由于异步等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经与创建基于 https://github.com/JeffGos/urbanairsharp一个REST包装打转转

public LoginResponse Login()
    {
        return SendRequest(new LoginRequest(new Model.Login()));
    }

private static TResponse SendRequest<TResponse>(BaseRequest<TResponse> request) where TResponse : BaseResponse, new()
    {
        try
        {
            var requestTask = request.ExecuteAsync();

            return requestTask.Result;
        }
        catch (Exception e)
        {
            //Log.Error(request.GetType().FullName, e);

            return new TResponse()
            {
                Error = e.InnerException != null ? e.InnerException.Message : e.Message,
                Ok = false
            };
        }
    }

我能够调用登录方法从一个控制台应用程序完全正常,但如果我把它从一个MVC控制器,它通过code细步骤,但从来没有通过行

I am able to call the Login method absolutely fine from a console app but if I call it from an MVC controller, it steps through the code fine but never passes the line

var requestTask = request.ExecuteAsync();

我看过周围的主题,但不很明白,我怎么可以使用这些方法从一个web应用程序?登录()方法不是异步,所以我不明白为什么它会从我的MVC动作失败(也非异步)?

I have read around the subject but dont quite understand how I can use these methods from a web app? The Login() method is not async so I dont see why it would fail from my MVC action (also non-async)?

感谢

推荐答案

var requestTask = request.ExecuteAsync();
return requestTask.Result;

导致您的code死锁。你与呼叫阻塞同步异步方法 Task.Result 这就是为什么的 你不应该在异步code座。相反,你需要在IR异步等待与等待。这将有效地使之成为您的通话链异步还有:

Is causing your code to deadlock. You're blocking an async method synchronously with the call to Task.Result That's why you shouldn't block on async code. Instead, you need to asynchronously wait on ir with await. This will effectively make your call chain become async as well:

public Task<LoginResponse> LoginAsync()
{
    return SendRequestAsync(new LoginRequest(new Model.Login()));
}

private static async Task<TResponse> SendRequestAsync<TResponse>(BaseRequest<TResponse> request) where TResponse : BaseResponse, new()
{
    try
    {
        return await request.ExecuteAsync();
    }
    catch (Exception e)
    {
        //Log.Error(request.GetType().FullName, e);

        return new TResponse()
        {
            Error = e.InnerException != null ? e.InnerException.Message : e.Message,
            Ok = false
        };
    }
}

如果你不能改变你的调用链,成为异步,使用同步API来代替。

In case you can't change your call chain to become asynchronous, use a synchronous API instead.

这篇关于从MVC控制器调用方法挂起由于异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆