在发出http请求时接收TaskCanceledException

问题描述 投票:0回答:1

我在收到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());
            }
        }
    }
}

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

c# xamarin async-await task httpclient
1个回答
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);
}
© www.soinside.com 2019 - 2024. All rights reserved.