public void TryThreeTimes(Action action)
{
var tries = 3;
while (true) {
try {
action();
break;
} catch {
if (--tries == 0)
throw;
Thread.Sleep(1000);
}
}
}
然后您将调用:
TryThreeTimes(DoSomething)
...或者...
TryThreeTimes(() => DoSomethingElse(withLocalVariable))
一个更加灵活的选项:
public void DoWithRetry(Action action, TimeSpan sleepPeriod, int tryCount = 3)
{
if (tryCount <= 0)
throw new ArgumentOutOfRangeException(nameof(tryCount));
while (true) {
try {
action();
break;
} catch {
if (--tryCount == 0)
throw;
Thread.Sleep(sleepPeriod);
}
}
}
用作:
DoWithRetry(DoSomething, TimeSpan.FromSeconds(2), tryCount: 10)
一个更现代化的版本,支持async/await:
public async Task DoWithRetryAsync(Func<Task> action, TimeSpan sleepPeriod, int tryCount = 3)
{
if (tryCount <= 0)
throw new ArgumentOutOfRangeException(nameof(tryCount));
while (true) {
try {
await action();
return;
} catch {
if (--tryCount == 0)
throw;
await Task.Delay(sleepPeriod);
}
}
}
应该这样使用:
await DoWithRetryAsync(DoSomethingAsync, TimeSpan.FromSeconds(2), tryCount: 10);