【问题标题】:Why is this exception happening? (TaskCanceledException )为什么会发生这种异常? (任务取消异常)
【发布时间】:2018-12-02 03:41:55
【问题描述】:

我遇到了 .NET HttpClient 类的问题。有时下面的 sn-p 会抛出 TaskCanceledException,我无法调试它,因为它是随机的(我运气不好,Apple 为此拒绝了我的 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;
        }
    }
}

【问题讨论】:

  • 每当您看到类似xxxAsync(...).Result 的内容时,您几乎可以保证您做错了什么
  • 那么,我可以让这个方法以其他方式同步吗?
  • 在我们回答之前,我们需要确定您所说的 make this method sync in another way 是什么意思,您是否希望这将您的线程返回到线程池并等待它返回(用于可伸缩性或 UI 异步目的)?反过来又迫使async await 模式在调用链中向上。或者你只想把它变成一个普通的同步方法?
  • 我要UI线程等他回来
  • @TheGeneral 仅供参考:那个答案不正确(假设他使用默认的NSUrlSessionHandler):stackoverflow.com/a/53229363/4984832

标签: c# xamarin httpclient


【解决方案1】:

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

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

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

    如果需要,每个请求都可以设置为特定的超时时间,如 HttpClient 超时在更高级别

【讨论】:

    猜你喜欢
    • 2011-11-12
    • 2021-08-14
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    • 2010-12-24
    相关资源
    最近更新 更多