我需要使用HttpClient
调用CancellationToken
方法:
var result = await client.GetAsync(url, token);
我的方法中有这样的东西:
public async Task<bool> CheckHashAsync(string cpf, string hash, CancellationToken token)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ApiUrls.Base);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var url = $"{ApiUrls.DeviceCheck}/{cpf}/{hash}";
var result = await client.GetAsync(url, token);
if (result.IsSuccessStatusCode)
{
...
}
return false;
}
如果我按这样调用方法,可以:
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(Base.TASK_CANCELED_LOGIN_TIME));
await Base.Instance.CheckHashAsync(cpf, hash, cts.Token);
但是,如果像这样创建CancellationTokenSource
:
ctsTwo = GetCancellationToken("Login");
public static CancellationTokenSource GetCancellationToken(string action)
{
switch(action)
{
case "Login":
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(TASK_CANCELED_LOGIN_TIME));
return cts;
}
}
}
然后调用方法,不工作:
await Base.Instance.CheckHashAsync(cpf, hash, ctsTwo.Token);
只要它调用GetAsync
方法,它就会返回TaskCancelledException
,就像未设置CancelAfter
方法一样。
有人可以解释为什么会这样吗?