方法一
var httpClient = new HttpClient();
var task = httpClient.GetStringAsync("https://www.baidu.com");
if (task == await Task.WhenAny(task, Task.Delay(5000)))
{
string resp = await task;
Console.WriteLine(resp);
}
else
{
Console.WriteLine("task timeout");
}
方法二
var httpClient = new HttpClient();
var tcs = new TaskCompletionSource<bool>();
using (var cts = new CancellationTokenSource(5000))
{
var task = httpClient.GetStringAsync("https://www.baidu.com");
using (cts.Token.Register(() => tcs.TrySetResult(true)))
{
if (task == await (Task.WhenAny(task, tcs.Task)))
{
string resp = await task;
Console.WriteLine(resp);
}
else
{
Console.WriteLine("task timeout");
}
}
}
网友评论