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