From bd57bf490ddfe05004de02f30657d1359adc2dcc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 9 Oct 2022 14:31:52 -0500 Subject: use CancellationTokens --- src/slskd/Common/Retry.cs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Retry.cs b/src/slskd/Common/Retry.cs index eccb6b62..2f7b24cd 100644 --- a/src/slskd/Common/Retry.cs +++ b/src/slskd/Common/Retry.cs @@ -19,6 +19,7 @@ namespace slskd { using System; using System.Collections.Generic; + using System.Threading; using System.Threading.Tasks; /// @@ -34,14 +35,15 @@ namespace slskd /// An action to execute on failure. /// The maximum number of retry attempts. /// The maximum delay in milliseconds. + /// The token to monitor for cancellation requests. /// The execution context. - public static async Task Do(Func task, Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) + public static async Task Do(Func task, Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue, CancellationToken cancellationToken = default) { await Do(async () => { await task(); return Task.FromResult(null); - }, isRetryable, onFailure, maxAttempts, maxDelayInMilliseconds); + }, isRetryable, onFailure, maxAttempts, maxDelayInMilliseconds, cancellationToken); } /// @@ -52,9 +54,10 @@ namespace slskd /// An action to execute on failure. /// The maximum number of retry attempts. /// The maximum delay in miliseconds. + /// The token to monitor for cancellation requests. /// The Type of the logic return value. /// The execution context. - public static async Task Do(Func> task, Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) + public static async Task Do(Func> task, Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue, CancellationToken cancellationToken = default) { isRetryable ??= (_, _) => true; onFailure ??= (_, _) => { }; @@ -63,12 +66,17 @@ namespace slskd for (int attempts = 0; attempts < maxAttempts; attempts++) { + if (cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(); + } + try { if (attempts > 0) { var (delay, jitter) = Compute.ExponentialBackoffDelay(attempts, maxDelayInMilliseconds); - await Task.Delay(delay + jitter); + await Task.Delay(delay + jitter, cancellationToken); } return await task(); -- cgit v1.2.3