实现可设置超时的Task

11/23/2018 csharp

一个扩展方法就可以搞定。

public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan 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;  // Very important in order to propagate exceptions
        }
        else
        {
            throw new TimeoutException("The operation has timed out.");
        }
    }
}

public static async Task TimeoutAfter(this Task task, TimeSpan timeout)
{

    using (var timeoutCancellationTokenSource = new CancellationTokenSource())
    {

        var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
        if (completedTask == task)
        {
            timeoutCancellationTokenSource.Cancel();
            await task;  // Very important in order to propagate exceptions
        }
        else
        {
            throw new TimeoutException("The operation has timed out.");
        }
    }
}

c# - Asynchronously wait for Task{T} to complete with timeout - Stack Overflow (opens new window)

更新时间: Friday, March 12, 2021 22:54