public async Task ExecuteAsync(BackgroundProcessContext context) { for (var i = 0; i <= MaxRetryAttempts; i++) { try { await InnerTask.ExecuteAsync(context).ConfigureAwait(false); return; } catch (OperationCanceledException) when(context.IsShutdownRequested) { throw; } catch (Exception ex) { // Break the loop after the retry attempts number exceeded. if (i >= MaxRetryAttempts - 1) { throw; } var nextTry = DelayCallback(i); var logLevel = GetLogLevel(i); _logger.Log( logLevel, // ReSharper disable once AccessToModifiedClosure () => $"Error occurred during execution of '{InnerTask}' process. Execution will be retried (attempt {i + 1} of {MaxRetryAttempts}) in {nextTry} seconds.", ex); await Task.Delay(nextTry, context.CancellationToken).ConfigureAwait(false); if (context.IsShutdownRequested) { break; } } } }