分离数据检索代码后异步请求无效

时间:2014-08-24 20:16:37

标签: asp.net-mvc asynchronous asp.net-web-api async-await

我试图在查询webapi后显示一些结果 -

public async Task<ActionResult> Get()
    {
        string _address = "someurl";
        string results = null;

        HttpClient client = new HttpClient(new OAuthMessageHandler(new HttpClientHandler()));
        HttpResponseMessage responseTask = await client.GetAsync(_address);

        if (responseTask.IsSuccessStatusCode)
        {
            results = await responseTask.Content.ReadAsStringAsync();
        }

        ResultModel model = JsonConvert.DeserializeObject<ResultModel>(results);

        return View(model);
    }

此代码工作正常,我可以从“someurl”网址中读取结果。现在,当我重新编写代码如下(通过将异步数据检索移动到另一个函数)时,它将停止工作。它永远需要查询,不会返回任何结果。这是因为一些死锁还是我没有正确使用异步。

public ActionResult Get()
{
        string _address = "someurl";
        Task<string> results = HttpClientService.HttpClientService.GetRequest(_address);

        IEnumerable<ResultModel> model  = JsonConvert.DeserializeObject<IEnumerable<ResultModel>>(results.Result);

        return View(model);
}

public static class HttpClientService
{
    public static async Task<string> GetRequest(string Url)
    {
        HttpClient client = new HttpClient(new OAuthMessageHandler(new HttpClientHandler()));
        HttpResponseMessage responseTask = await client.GetAsync(Url);

        if (responseTask.IsSuccessStatusCode)
        {
            return await responseTask.Content.ReadAsStringAsync();

        }
        else
        {
            return "Sorry buddy, cannot retrieve the requested data!";
        }
    }
}

请告诉我这里我做错了什么。我是Async实现的新手。

1 个答案:

答案 0 :(得分:1)

您应该等待GetRequest方法。否则,你正在打败异步处理的目的,即释放线程以便它可以做其他工作。在这种情况下,当您通过results.Result。

请求结果时,您仍然会阻止该线程
public async Task<ActionResult> Get()
{
        string _address = "someurl";
        string results = await HttpClientService.HttpClientService.GetRequest(_address);

        IEnumerable<ResultModel> model  = JsonConvert.DeserializeObject<IEnumerable<ResultModel>>(results);

        return View(model);
}

坦率地说,我不确定为什么你的代码没有返回,但即使它工作正常,以这种方式做异步请求也没有意义。