美文网首页
c# task 设置超时

c# task 设置超时

作者: lesliefang | 来源:发表于2021-05-30 22:47 被阅读0次

    方法一

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

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

    相关文章

      网友评论

          本文标题:c# task 设置超时

          本文链接:https://www.haomeiwen.com/subject/svzmsltx.html