c# でロジックをエレガントに再試行する論理を実現します
ソフトウェア開発では、一部の操作を正常に完了するために複数回試行する必要がある場合があります。従来の方法は、通常、次のコードなど、明示的な再試行時間を使用して
サイクルを使用します。
while
この方法により、操作が繰り返し定義されることが保証されていますが、さまざまな場合にコンパイルが複雑になる可能性があります。より一般的な方法では、より簡潔で再利用可能なソリューションを提供できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | int retries = 3;
while (true)
{
try
{
DoSomething();
break ;
}
catch
{
if (--retries == 0) throw ;
else Thread.Sleep(1000);
}
}
|
ログイン後にコピー
<入>クラス
を紹介します
目標は、再利用可能なクラスを作成することです。これは、委員会をパラメーターとして受け入れ、再テストブロックで操作を実行することです。次のコードは、可能な実装を提供します:Retry
<<>class Retry
を使用します
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public static class Retry
{
public static void Do(Action action, TimeSpan retryInterval, int maxAttemptCount = 3)
{
Do(() => { 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
{
return action();
}
catch (Exception ex)
{
exceptions.Add(ex);
if (attempted < maxAttemptCount -1)
{
Thread.Sleep(retryInterval);
}
}
}
throw new AggregateException(exceptions);
}
}
|
ログイン後にコピー
この方法は、再試行ロジックを実現するためにさまざまな方法で使用できます。
示されているように、この方法は、再試行を処理する柔軟な方法を提供します。これにより、試行回数、再試行間隔、および実行する操作が指定できます。 Retry
以上がC#にRetryロジックをエレガントに実装する方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。