天天看点

为重复使用的HttpClient对象动态修改Timeout

最近博客园被**了, 赶紧水一文支持一下博客园,加油!

当<code>HttpClient</code>被使用过之后, 在修改它们的属性会抛出错误<code>This instance has already started one or more requests. Properties can only be modified before sending the first request</code>.

单例 <code>HttpClient</code> 对象, 我们要修改它的 <code>Timeout</code>

Scope生命周期的 <code>HttpClient</code>, 我们要修改它的 <code>Timeout</code>

可以把 <code>HttpClient</code> 的生命周期改成 <code>Transient</code>, 并且每次要用的时候都从 <code>IServiceProvider</code> 获取.

在注册 <code>HttpClient</code> 的时候把它的 <code>Timeout</code> 修改为 <code>System.Threading.Timeout.InfiniteTimeSpan</code>

然后调用的地方使用自己的<code>CancellationToken</code>来实现即可, 其实<code>HttpClient.Timeout</code>在内部也是一样的方式.

继续阅读