private static void DoWithRetries(Action action, int tryCount = 3, string addMessage = "") { bool success = false; int tryIndex = 0; do { try { action(); success = true; } catch (Exception ex) { tryIndex++; // any sort of logging Console.WriteLine($"Operation [{addMessage}] failed. Attempt nr. [{tryIndex}]. Exception: [{ex.Message}]"); if (tryIndex >= tryCount) throw; } } while (!success); }
Usage example:
DoWithRetries(() => { if (rng.Next(0, 3) > 0) // 33% { throw new Exception("random exception"); } Console.WriteLine("Operation finished successfully"); }, 5, "Random Exception Thrower");
Result:
Operation [Random Exception Thrower] failed. Attempt nr. [1]. Exception: [random exception]
Operation [Random Exception Thrower] failed. Attempt nr. [2]. Exception: [random exception]
Operation finished successfully