异步方法不返回asp.net mvc 4

时间:2013-04-16 10:52:37

标签: c# asp.net asp.net-mvc asynchronous

我遇到了我实现的异步方法的问题。该方法基本上对资源进行HttpRequest,并在请求成功时反序列化字符串。我为该方法编写了一个测试,它可以工作。但是当我从控制器调用它时,该方法永远不会返回?

    public async Task<IEnumerable<T>> Get()
    {
        try
        {
            var resourceSegmentUri = new Uri(_uri, UriKind.Relative);

            var response = await _client.GetAsync(resourceSegmentUri);

            if (response.IsSuccessStatusCode)
            {
                var submission = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<IEnumerable<T>>(submission);
            }

            if (response.Content != null)
            {
                var message = response.Content.ReadAsStringAsync();
                throw new WebException(message.Result, (WebExceptionStatus)response.StatusCode);
            }

        }
        catch (WebException e)
        {
            Logger.Error("GET Request failed with status: {0}", e.Status);
            throw;
        }

        throw new Exception();
    }

永不返回的代码:

public ActionResult Index()
{
   var api = new Api();
   var test = api.Get().Result; //Never returns
   return View();
}

测试有效:

[Test]
public void GetShouldReturnIfSuccessfulRequest()
{
    var api = new Api();
    var submission = api.Get();

    Console.WriteLine(JsonConvert.SerializeObject(submission));
    Assert.NotNull(submission);
}

有谁知道这个问题?

1 个答案:

答案 0 :(得分:12)

您遇到了死锁,因为您在控制器操作中调用了.Result

如果您使用async/await,那么您也必须使用异步操作。

所以这样的事情应该解决它:

public async Task<ActionResult> Index()
{
  var api = new Api();
  var test = await api.Get(); // Should return
}

这里有一篇关于此的综合文章:Using Asynchronous Methods in ASP.NET MVC 4