取消与陌生人行为

时间:2017-12-07 10:39:57

标签: c# xamarin.android task httprequest httpclient

我需要使用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方法一样。

有人可以解释为什么会这样吗?

0 个答案:

没有答案