Re-using HttpClient but with a different Timeout setting per request?

后端 未结 2 721
悲&欢浪女
悲&欢浪女 2021-01-03 17:54

In order to reuse open TCP connections with HttpClient you have to share a single instance for all requests.

This means that we cannot simply i

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 18:23

    Under the hood, HttpClient just uses a cancellation token to implement the timeout behavior. You can do the same directly if you want to vary it per request:

    var cts = new CancellationTokenSource();
    cts.CancelAfter(TimeSpan.FromSeconds(30));
    await httpClient.GetAsync("http://www.google.com", cts.Token);
    

    Note that the default timeout for HttpClient is 100 seconds, and the request will still be canceled at that point even if you've set a higher value at the request level. To fix this, set a "max" timeout on the HttpClient, which can be infinite:

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

提交回复
热议问题