在发出http请求时接收TaskCanceledException

时间:2017-12-14 21:11:39

标签: c# xamarin async-await task httpclient

我在发出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());
            }
        }
    }
}

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

1 个答案:

答案 0 :(得分:4)

这是预期的行为,默认情况下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);
}