为什么会发生这种异常? (TaskCanceledException)

时间:2018-12-02 03:41:56

标签: c# xamarin httpclient

.NET HttpClient类遇到问题。有时下面的代码片段会抛出一个TaskCanceledException,但由于随机性,我无法调试此代码(我很不幸,苹果公司因此而拒绝了我的Xamarin应用)。有人可以向我解释这种例外的原因吗?

 public static HttpResultModel RecoveryPassword(string email)
    {
        HttpClient httpClient = new HttpClient();

        try
        {
            var url = String.Format(Constants.SERVER_ADDRESS + "/user/forgotPassword/{0}/", email);

            var request = new HttpRequestMessage(new HttpMethod("POST"), url)
            {
                Content = new StringContent(email, Encoding.UTF8, "application/json"),
            };

            //to be more specific, this line throws the exception
            var result = httpClient.SendAsync(request).Result;

            string message = result.Content.ReadAsStringAsync().Result;

            if (result.IsSuccessStatusCode)
            {
                var response = JsonConvert.DeserializeObject<HttpResultModel>(message);
                response.OperationSuccess = true;
                return response;
            }
            else
            {
                var response = JsonConvert.DeserializeObject<HttpResultModel>(message);
                response.OperationSuccess = false;
                return response;
            }
        }

        catch (Exception ex)
        {
            throw ex;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这是由于以下两个原因之一:

  1. 服务器断开连接
  2. Http客户端超时。 HttpClient的默认值为100秒。 您可以将其设置为无限的时间跨度。

    httpClient.Timeout = System.Threading.Timeout.InfiniteTimeSpan;

    然后可以根据需要将每个请求设置为特定的超时时间,例如HttpClient 超时程度更高