C# 任务设置超时取消

        public static async Task<TResult> TaskTimeoutAfter<TResult>(this Task<TResult> task, int timeout)
        {
            using (var timeoutCancellationTokenSource = new CancellationTokenSource())
            {
                var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
                if (completedTask == task)
                {
                    timeoutCancellationTokenSource.Cancel();
                    return await task;
                }

                throw new TimeoutException("The operation has timed out");
            }
        }

 

posted @ 2023-08-21 19:28  log9527  阅读(82)  评论(0编辑  收藏  举报