我希望在我的代码中指定的超时90秒之前运行异步任务时取消HttpClient请求:
CancellationTokenSource cts = new CancellationTokenSource();
public async Task<string> GetData()
{
try
{
CookieContainer cookies = new CookieContainer();
cookies.SetCookies(uri, strCookie);
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient client = new HttpClient(handler);
client.Timeout = new TimeSpan(0, 0, 90);
var response = await client.GetAsync(uri,HttpCompletionOption.ResponseHeadersRead,cts.Token);
res = await response.Content.ReadAsStringAsync();
return res;
}
catch (Exception ex)
{
throw ex;
}
}
public void CancelTask()
{
cts.Cancel();
}
在执行GetData()
方法的某个时间点我正在调用CancelTask()
方法立即取消请求,它会一直持续到90秒的超时。
是否可以在达到超时值之前取消任务。我这样做是为了解决我的应用程序中的特定场景。