簡體   English   中英

由於異步等待,MVC控制器的調用方法掛起

[英]Calling method from MVC controller hangs due to async await

我一直在根據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
            };
        }
    }

我可以從控制台應用程序完全調用Login方法,但是如果我從MVC控制器調用它,它會逐步通過代碼,但永遠不會通過該行

var requestTask = request.ExecuteAsync();

我已經閱讀了有關該主題的內容,但還不太了解如何從Web應用程序中使用這些方法? Login()方法不是異步的,所以我看不到為什么它會由於我的MVC操作而失敗(也是非異步的)?

謝謝

這個:

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

導致您的代碼陷入僵局。 您正在與Task.Result的調用同步地阻塞異步方法,這就是為什么您不應該阻塞異步代碼的原因 相反,您需要使用await異步在ir上await ir。 這也將有效地使您的呼叫鏈也變得異步:

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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM