有时我需要在放弃之前重试几次操作.我的代码是这样的:
Occasionally I have a need to retry an operation several times before giving up. My code is like:
int retries = 3; while(true) { try { DoSomething(); break; // success! } catch { if(--retries == 0) throw; else Thread.Sleep(1000); } }我想在一个通用的重试函数中重写这个:
I would like to rewrite this in a general retry function like:
TryThreeTimes(DoSomething);在 C# 中可以吗?TryThreeTimes() 方法的代码是什么?
Is it possible in C#? What would be the code for the TryThreeTimes() method?
推荐答案简单地重试相同调用的一揽子 catch 语句如果用作一般异常处理机制可能是危险的.话虽如此,这里有一个基于 lambda 的重试包装器,您可以将其与任何方法一起使用.我选择将重试次数和重试超时作为参数考虑在内,以获得更大的灵活性:
Blanket catch statements that simply retry the same call can be dangerous if used as a general exception handling mechanism. Having said that, here's a lambda-based retry wrapper that you can use with any method. I chose to factor the number of retries and the retry timeout out as parameters for a bit more flexibility:
public static class Retry { public static void Do( Action action, TimeSpan retryInterval, int maxAttemptCount = 3) { Do<object>(() => { action(); return null; }, retryInterval, maxAttemptCount); } public static T Do<T>( Func<T> action, TimeSpan retryInterval, int maxAttemptCount = 3) { var exceptions = new List<Exception>(); for (int attempted = 0; attempted < maxAttemptCount; attempted++) { try { if (attempted > 0) { Thread.Sleep(retryInterval); } return action(); } catch (Exception ex) { exceptions.Add(ex); } } throw new AggregateException(exceptions); } }您现在可以使用此实用程序方法来执行重试逻辑:
You can now use this utility method to perform retry logic:
Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));或:
Retry.Do(SomeFunctionThatCanFail, TimeSpan.FromSeconds(1));或:
int result = Retry.Do(SomeFunctionWhichReturnsInt, TimeSpan.FromSeconds(1), 4);或者您甚至可以进行 async 重载.
Or you could even make an async overload.
更多推荐
编写重试逻辑的最简洁方法?
发布评论