在C#中使用CancellationTokenSource设置超时时间

C#中的CancellationTokenSource类可以通过CancelAfter方法设置超时时间,因此可以用于异步方法中的超时设置。

测试代码:

class Program
{
    static async Task Main(string[] args)
    {
        using (var tokenSource = new CancellationTokenSource())
        {
            //设置超时时间
            tokenSource.CancelAfter(1000);

            var stopWatch = new Stopwatch();
            stopWatch.Start();
            await SampleFunctionAsync(tokenSource.Token);
            stopWatch.Stop();

            if (tokenSource.Token.IsCancellationRequested)
            {
                Console.WriteLine(@"IsCancellationRequested");
            }

            Console.WriteLine($"SampleFunctionAsync takes {stopWatch.ElapsedMilliseconds}ms.");
        }

        Console.ReadKey();
    }

    private static async Task SampleFunctionAsync(CancellationToken token)
    {
        try
        {
            await Task.Delay(2000, token);
        }
        catch (Exception e)
        {
            Console.WriteLine($@"SampleFunctionAsync exception: {e.Message}");
        }
    }
}

测试结果:

posted @ 2021-06-17 10:21  xhubobo  阅读(644)  评论(0编辑  收藏  举报