Asynchronously wait for Task to complete with timeout

后端 未结 16 2007
天命终不由人
天命终不由人 2020-11-21 17:49

I want to wait for a Task to complete with some special rules: If it hasn\'t completed after X milliseconds, I want to display a message to the user. And

16条回答
  •  借酒劲吻你
    2020-11-21 18:35

    Here's a extension method version that incorporates cancellation of the timeout when the original task completes as suggested by Andrew Arnott in a comment to his answer.

    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();
                return await task;  // Very important in order to propagate exceptions
            } else {
                throw new TimeoutException("The operation has timed out.");
            }
        }
    }
    

提交回复
热议问题