Skip to main content
 首页 » 编程设计

c#之多次重试的好方法

2024年02月20日12powertoolsteam

我经常遇到一些情况,如果某些操作失败,我必须重试,在一定次数后放弃,并在两次尝试之间短暂休息。

有没有办法创建一个“重试方法”,使我不必每次都复制代码?

请您参考如下方法:

厌倦了一遍又一遍地复制/粘贴相同的代码,所以我创建了一个方法来接受必须完成的任务的委托(delegate)。在这里:

//  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); 

在这个例子中,我附加了一个被一些外部进程锁定的文件,写入它的唯一方法是重试几次,直到进程完成......

我肯定很乐意看到处理这种特定模式(重试)的更好方法。

编辑:我查看了 Gallio在另一个答案中,它真的很棒。看这个例子:

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(); }); 

它无所不能。它甚至会在您编写代码时照看您的 child :) 但是,我力求简单,并且仍在使用 .NET 2.0。所以我想我的示例对您仍然会有一些用处。