I need to call a HttpClient
method with CancellationToken
:
var result = await client.GetAsync(url, token);
I have something like this in my method:
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;
}
If I call the method like this, it works:
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(Base.TASK_CANCELED_LOGIN_TIME));
await Base.Instance.CheckHashAsync(cpf, hash, cts.Token);
But, if create the CancellationTokenSource
like this:
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;
}
}
}
And then call the method, it doesn't work:
await Base.Instance.CheckHashAsync(cpf, hash, ctsTwo.Token);
As soon as it calls the GetAsync
method, it return a TaskCancelledException
like the CancelAfter
method was not set.
Can anyone explain why this happens?