使用类型化的 HttpClient 创建 LinkedTokenSource

Creating LinkedTokenSource using typed HttpClient

你好,我想了解如何根据超时 属性 集使用类型 HttpClient(使用 IHttpClientFactory)扩展创建 LinkedTokenSource 和任何其他 CancellationToken(s):

注册

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient("someClient",(client)=>
    {
        client.Timeout=Timespan.FromSeconds(15);
    });
}

用法

public class SomeService
{
    private IHttpClientFactory factory;
    public SomeService(IHttpClientFactory factory)
    {
        this.factory = factory;
    }
    public async Task MethodWithAggreatedToken(CancellationToken token = default)
    {
        CancellationToken additionalToken = token;
        if (additionalToken == default)
        {
            CancellationTokenSource source = new CancellationTokenSource();
            source.CancelAfter(Timespan.FromSeconds(10));
        }
        var client = factory.CreateClient("someService");
        HttpRequestMessage msg = new HttpRequestMessage(.....);
        using (var cts = CancellationTokenSource.CreateLinkedTokenSource(additionalToken,[DI token])
        {
            var response = await client.SendAsync(msg, cts.Token);
            //can i created a linked token?
            //and if not who gets priority : 
            //1.the token set via the  `Timeout` property set in Startup
            //2.the one injected in the `SendAsync`
        }
    }
}

在上面的例子中,我希望能够为我的 typed HttpClient 设置一个通用的 Timeout ,它将用于我想知道的许多 methods.Now如果:

我想知道我是否可以组合标记以及谁会被覆盖(SendAsyncTimeout

There is a way to add additional Token(s) above this general condition thus creating new LinkedTokenSource(s)

是的,您可以 link 任意数量 CancellationTokenSource。因为 CreateLinkedTokenSource returns a CancellationTokenSource 这就是你可以使用链接的原因。

您还可以同时 link 多个 CancellationTokenSource 秒,方法是使用接受 params.

的重载

Who gets priority if i set a CancellationToken in the HttpClient.SendAsync while also declaring the Timeout property in the services.AddHttpClient.

HttpClient的TimeoutRemarks明确说明如下:

The same timeout will apply for all requests using this HttpClient instance. You may also set different timeouts for individual requests using a CancellationTokenSource on a task. Note that only the shorter of the two timeouts will apply.


编辑:反映到 如何从 HttpClient 中提取 token

总之就是不暴露

如果您查看 HttpClient (.NET Framework implementation, .NET Core implementation) 的源代码,您会发现一个名为 pendingRequestsCts

CancellationTokenSource 私有字段

SendAsync / SendAsyncCore 方法中,pendingRequestsCts 被 link 编辑到给定操作的 CancellationToken

如果是 .NET Framework,它是通过简单的 CreateLinkedTokenSource 调用完成的。
另一方面,如果是 .NET Core,则要复杂一些。 PrepareCancellationTokenSource method 包含 linked CTS 和超时计算。