C#HttpClient GetStringAsync任务早期返回

时间:2016-01-25 10:26:31

标签: c# asp.net async-await httpclient dotnet-httpclient

我正在开发一个ASP.NET项目,我正在使用我们创建的自定义REST服务来获取站点的JSON数据。我正在使用HTTPClient来调用REST服务。但是当我调用我在下面创建的ProcessRestMethod例程时,有时任务将返回正确的结果,但有时任务将不会完成执行并且例程将返回。我在异步调用中缺少什么?我的ProcessRestMethod代码如下。感谢:

private string ProcessRestMethod(string methodName, string parameters)
{
    string result = "";
    using (HttpClient httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        string strParams = parameters;

        if ((!String.IsNullOrEmpty(parameters)) && (parameters.IndexOf('?') != 0))
            strParams = "?" + parameters;


        var task = httpClient.GetStringAsync(baseUri + methodName + strParams);
        task.Wait();
        task.ContinueWith((t) =>
        {
            var tresult = t.Result;
            result = tresult;
        });
    }
    if (result == "")
        result = "{\"status\":{\"code\":1000,\"message\":\"Unkown Error Ocured\"}}";
    return result;
}

2 个答案:

答案 0 :(得分:1)

您需要做的就是获取任务的Result属性 - 这将等待它完成并返回结果。

您之前所做的是开始"继续"获得结果的任务。这将导致在不同的线程中获得结果,因此您具有所描述的竞争条件。

  private string ProcessRestMethod(string methodName, string parameters)
  {
        string result = "";
        using (HttpClient httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            string strParams = parameters;

            if ((!String.IsNullOrEmpty(parameters)) && (parameters.IndexOf('?') != 0))
                strParams = "?" + parameters;


            var task = httpClient.GetStringAsync(baseUri + methodName + strParams);
            // Just call `task.Result` here :)
            result = task.Result;
        }
        if (result == "")
            result = "{\"status\":{\"code\":1000,\"message\":\"Unkown Error Ocured\"}}";
        return result;
    }

答案 1 :(得分:1)

使用

尝试以下操作
  

异步/ AWAIT

    private async Task<string> ProcessRestMethod(string methodName, string parameters)
    {
        string result = "";
        using (HttpClient httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            string strParams = parameters;

            if ((!String.IsNullOrEmpty(parameters)) && (parameters.IndexOf('?') != 0))
                strParams = "?" + parameters;


            result = await httpClient.GetStringAsync(baseUri + methodName + strParams);

        }
        if (result == "")
            result = "{\"status\":{\"code\":1000,\"message\":\"Unkown Error Ocured\"}}";
        return result;
    }

您可以在此处阅读有关任务,异步和等待的更多信息 https://www.simple-talk.com/dotnet/.net-tools/c-async-what-is-it,-and-how-does-it-work/ http://www.dotnetperls.com/async 重要的是,这个解释了最好的 https://msdn.microsoft.com/library/hh191443.aspx