public static Task RetryOnThrottle(this IMessageSender sender, Func <IMessageSender, Task> action, TimeSpan delay, int maxRetryAttempts, int retryAttempts = 0) { var task = action(sender); return(task.ContinueWith(async t => { var exception = ExceptionDispatchInfo.Capture(t.Exception?.InnerException); var serverBusy = exception.SourceException is InvalidOperationException; if (serverBusy && retryAttempts < maxRetryAttempts) { await Task.Delay(delay); await sender.RetryOnThrottle(action, delay, maxRetryAttempts, ++retryAttempts); } else if (t.IsFaulted) { exception.Throw(); } }) .Unwrap()); }