c# task 设置超时

方法一

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();

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");
        }
    }
}

方法二的好处是如果异步方法可以传递 CancellationToken 则超时后可以自动取消异步方法的执行。

你可能感兴趣的:(c# task 设置超时)