【问题标题】:Receiving TaskCanceledException when making http request发出 http 请求时收到 TaskCanceledException
【发布时间】:2018-05-29 01:27:05
【问题描述】:

我在发出 Http 请求时收到了System.Threading.Tasks.TaskCanceledException

public async Task<CommonResult<T>> GetRequest<T>(TokenModel token, string url)
{
    using (var client = new HttpClient())
    {
        client.MaxResponseContentBufferSize = int.MaxValue;
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.TokenType, token.AccessToken);

        var response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            return await OK<T>(response);
        }
        else
        {
            //The response is authorized but some other error.
            if (IsAuthorized(response.StatusCode))
                return Error<T>(response.StatusCode.ToString());

            //Unable to refresh token.
            if (!await RenewToken(token))
                return Error<T>("Fail to refresh token");

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(GlobalData.Token.TokenType, GlobalData.Token.AccessToken);
            response = await client.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                return await OK<T>(response);
            }
            else
            {
                return Error<T>(response.StatusCode.ToString());
            }
        }
    }
}

当我调试服务器代码而不继续时会发生这种情况。这是自然行为还是我在客户端代码中遗漏了什么?

【问题讨论】:

  • 是否有 InnerException?
  • 否为空。消息说“任务已取消”
  • 您可能遇到了 HTTP 超时。你在叫什么?它是否手动工作,例如来自邮递员?如果是 Azure,它的硬超时时间为 230 秒。

标签: c# xamarin async-await task httpclient


【解决方案1】:

这是预期的行为,默认情况下HttpClient 设置timeout of 100 seconds


HttpClient 超时

您可以调整 HttpClient 并设置自定义超时持续时间。例如,您可以设置InfiniteTimeSpan 以防止发生超时。

client.Timeout = Timeout.InfiniteTimeSpan;


HttpClient 请求超时

您还可以使用CancellationTokenSource 额外定义每个请求的超时时间

using (var cts = new CancellationTokenSource(Timeout.InfiniteTimeSpan))
{
    await client.GetAsync(url, cts.Token).ConfigureAwait(false);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    相关资源
    最近更新 更多