【发布时间】:2020-07-22 05:11:50
【问题描述】:
您好,我想了解如何使用键入的HttpClient(使用IHttpClientFactory)扩展和任何其他CancellationToken(s)基于超时属性集创建LinkedTokenSource:
注册
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,这将在许多方法中使用。现在我想知道:
- 有一种方法可以在此一般条件之上添加额外的
Token(s),从而创建一个LinkedTokenSource - 如果我在
HttpClient.SendAsync中设置CancellationToken同时在services.AddHttpClient。
我想知道我是否可以组合令牌以及谁会被覆盖(SendAsync 或 Timeout)
【问题讨论】:
标签: asp.net-core httpclient cancellationtokensource cancellation-token