| | 1 | | namespace Songhay.Net; |
| | 2 | |
|
| | 3 | | /// <summary> |
| | 4 | | /// Defines timeout and cancellation support |
| | 5 | | /// for <see cref="HttpClient"/>. |
| | 6 | | /// </summary> |
| | 7 | | /// <seealso cref="DelegatingHandler" /> |
| | 8 | | /// <remarks> |
| | 9 | | /// 📖 see “Better timeout handling with HttpClient” |
| | 10 | | /// by @thomaslevesque [ https://github.com/thomaslevesque ] |
| | 11 | | /// [ https://thomaslevesque.com/2018/02/25/better-timeout-handling-with-httpclient/ ] |
| | 12 | | /// |
| | 13 | | /// </remarks> |
| | 14 | | public class TimeoutHandler : DelegatingHandler |
| | 15 | | { |
| | 16 | | /// <summary> |
| | 17 | | /// Gets or sets the default timeout. |
| | 18 | | /// </summary> |
| 0 | 19 | | public static TimeSpan DefaultTimeout { get; } = TimeSpan.FromSeconds(100); |
| | 20 | |
|
| | 21 | | /// <summary> |
| | 22 | | /// Gets or sets the request timeout. |
| | 23 | | /// </summary> |
| 0 | 24 | | public TimeSpan RequestTimeout { get; init; } = DefaultTimeout; |
| | 25 | |
|
| | 26 | | /// <summary> |
| | 27 | | /// Sends an HTTP request to the inner handler to send to the server as an asynchronous operation. |
| | 28 | | /// </summary> |
| | 29 | | /// <param name="request">The HTTP request message to send to the server.</param> |
| | 30 | | /// <param name="cancellationToken">A cancellation token to cancel operation.</param> |
| | 31 | | /// <returns> |
| | 32 | | /// The task object representing the asynchronous operation. |
| | 33 | | /// </returns> |
| | 34 | | protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, |
| | 35 | | CancellationToken cancellationToken) |
| 0 | 36 | | { |
| 0 | 37 | | using var cts = GetCancellationTokenSource(cancellationToken); |
| | 38 | | try |
| 0 | 39 | | { |
| 0 | 40 | | return await base |
| 0 | 41 | | .SendAsync(request, cts?.Token ?? cancellationToken) |
| 0 | 42 | | .ConfigureAwait(continueOnCapturedContext: false); |
| | 43 | | } |
| 0 | 44 | | catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) |
| 0 | 45 | | { |
| 0 | 46 | | throw new TimeoutException(); |
| | 47 | | } |
| 0 | 48 | | } |
| | 49 | |
|
| | 50 | | CancellationTokenSource? GetCancellationTokenSource(CancellationToken cancellationToken) |
| 0 | 51 | | { |
| 0 | 52 | | if (RequestTimeout == Timeout.InfiniteTimeSpan) |
| 0 | 53 | | { |
| | 54 | | // No need to create a CTS if there's no timeout |
| 0 | 55 | | return null; |
| | 56 | | } |
| | 57 | | else |
| 0 | 58 | | { |
| 0 | 59 | | var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| 0 | 60 | | cts.CancelAfter(RequestTimeout); |
| | 61 | |
|
| 0 | 62 | | return cts; |
| | 63 | | } |
| 0 | 64 | | } |
| | 65 | | } |