1

失敗した場合にいくつかの操作を再試行し、特定の回数後にあきらめ、試行の間に短い休憩を取る必要がある状況が常にあります。

毎回コードをコピーしないようにする「再試行メソッド」を作成する方法はありますか?

4

2 に答える 2

3

同じコードを何度もコピーして貼り付けるのに飽きたので、実行する必要のあるタスクのデリゲートを受け入れるメソッドを作成しました。ここにあります:

//  logger declaration (I use NLog)
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
delegate void WhatTodo();
static void TrySeveralTimes(WhatTodo Task, int Retries, int RetryDelay)
{
    int retries = 0;
    while (true)
    {
        try
        {
            Task();
            break;
        }
        catch (Exception ex)
        {
            retries++;
            Log.Info<string, int>("Problem doing it {0}, try {1}", ex.Message, retries);
            if (retries > Retries)
            {
                Log.Info("Giving up...");
                throw;
            }
            Thread.Sleep(RetryDelay);
        }
    }
}

それを使用するには、私は単に次のように書きます。

TrySeveralTimes(() =>
{
    string destinationVpr = Path.Combine(outdir, "durations.vpr");
    File.AppendAllText(destinationVpr, file + ",     " + lengthInMiliseconds.ToString() + "\r\n");
}, 10, 100);

この例では、外部プロセスでロックされたファイルを追加しています。ファイルを書き込む唯一の方法は、プロセスが完了するまでファイルを数回再試行することです...

この特定のパターンを処理する(再試行する)より良い方法を見てみたいと思います。

編集:私は別の答えでガリオを見ました、そしてそれは本当に素晴らしいです。この例を見てください:

Retry.Repeat(10) // Retries maximum 10 times the evaluation of the condition.
         .WithPolling(TimeSpan.FromSeconds(1)) // Waits approximatively for 1 second between each evaluation of the condition.
         .WithTimeout(TimeSpan.FromSeconds(30)) // Sets a timeout of 30 seconds.
         .DoBetween(() => { /* DoSomethingBetweenEachCall */ })
         .Until(() => { return EvaluateSomeCondition(); });

それはすべてを行います。あなたがコーディングしている間、それはあなたの子供を見さえします:)しかし、私は単純さを追求し、それでも.NET2.0を使用しています。ですから、私の例はまだあなたに役立つと思います。

于 2012-06-25T13:55:25.420 に答える
1

特定のドメイン要件に基づいてこのようなヘルパーを作成しましたが、一般的な出発点として、Gallioの実装を見てください。

http://www.gallio.org/api/html/T_MbUnit_Framework_Retry.htm

https://code.google.com/p/mb-unit/source/browse/trunk/v3/src/MbUnit/MbUnit/Framework/Retry.cs

http://interfaceingreality.blogspot.co.uk/2009/05/retryuntil-in-mbunit-v3.html

于 2012-06-25T14:08:23.150 に答える