我已按照示例here和here使用C#HttpClient成功处理超时但我无法使其正常工作!
var urls = new List<string> { "/success", "/willtimeout", "/success" };
var baseAddress = "http://endpoint";
var httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 0, 30);
httpClient.BaseAddress = new Uri(baseAddress);
foreach (var url in urls)
{
try
{
var cs = CancellationTokenSource.CreateLinkedTokenSource(CancellationToken.None);
cs.CancelAfter(new TimeSpan(0, 0, 3));
var result = await httpClient.GetAsync(urls, cs.Token);
Console.WriteLine("Success");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
此代码将打印
Success
A task was canceled.
A task was canceled.
如果不每次都创建新的HttpClient,我怎样才能正常工作?
答案 0 :(得分:0)
CreateLinkedTokenSource创建一个CancellationTokenSource,当任何源令牌处于取消状态时,该源将处于取消状态。
所以我猜这就是问题所在,每次只创建新的令牌源,不要将它链接到任何东西:
try
{
var cs = new CancellationTokenSource();
// ...