|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Diagnostics; |
| 6 | +using System.Runtime.CompilerServices; |
| 7 | +using System.Threading; |
| 8 | +using System.Threading.Tasks; |
| 9 | + |
| 10 | +namespace Microsoft.AspNetCore.Testing |
| 11 | +{ |
| 12 | + // Copied from https://github.com/aspnet/Extensions/blob/master/src/TestingUtils/Microsoft.AspNetCore.Testing/src/TaskExtensions.cs |
| 13 | + // Required because Microsoft.AspNetCore.Testing is not shipped |
| 14 | + internal static class TaskExtensions |
| 15 | + { |
| 16 | + public static async Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout, |
| 17 | + [CallerFilePath] string filePath = null, |
| 18 | + [CallerLineNumber] int lineNumber = default) |
| 19 | + { |
| 20 | + // Don't create a timer if the task is already completed |
| 21 | + // or the debugger is attached |
| 22 | + if (task.IsCompleted || Debugger.IsAttached) |
| 23 | + { |
| 24 | + return await task; |
| 25 | + } |
| 26 | + |
| 27 | + var cts = new CancellationTokenSource(); |
| 28 | + if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token))) |
| 29 | + { |
| 30 | + cts.Cancel(); |
| 31 | + return await task; |
| 32 | + } |
| 33 | + else |
| 34 | + { |
| 35 | + throw new TimeoutException(CreateMessage(timeout, filePath, lineNumber)); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + public static async Task TimeoutAfter(this Task task, TimeSpan timeout, |
| 40 | + [CallerFilePath] string filePath = null, |
| 41 | + [CallerLineNumber] int lineNumber = default) |
| 42 | + { |
| 43 | + // Don't create a timer if the task is already completed |
| 44 | + // or the debugger is attached |
| 45 | + if (task.IsCompleted || Debugger.IsAttached) |
| 46 | + { |
| 47 | + await task; |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + var cts = new CancellationTokenSource(); |
| 52 | + if (task == await Task.WhenAny(task, Task.Delay(timeout, cts.Token))) |
| 53 | + { |
| 54 | + cts.Cancel(); |
| 55 | + await task; |
| 56 | + } |
| 57 | + else |
| 58 | + { |
| 59 | + throw new TimeoutException(CreateMessage(timeout, filePath, lineNumber)); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + private static string CreateMessage(TimeSpan timeout, string filePath, int lineNumber) |
| 64 | + => string.IsNullOrEmpty(filePath) |
| 65 | + ? $"The operation timed out after reaching the limit of {timeout.TotalMilliseconds}ms." |
| 66 | + : $"The operation at {filePath}:{lineNumber} timed out after reaching the limit of {timeout.TotalMilliseconds}ms."; |
| 67 | + } |
| 68 | +} |
0 commit comments