Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 这是一种很好的方法,可以多次重试_C#_.net_Exception - Fatal编程技术网

C# 这是一种很好的方法,可以多次重试

C# 这是一种很好的方法,可以多次重试,c#,.net,exception,C#,.net,Exception,我经常遇到这样的情况:如果某些操作失败,我必须重试,在一定次数后放弃,并在尝试之间短暂休息 有没有办法创建一个“重试方法”,使我不必每次都复制代码?厌倦了一遍又一遍地复制/粘贴相同的代码,所以我创建了一个方法,接受必须完成的任务的委托。这是: // logger declaration (I use NLog) private static readonly Logger Log = LogManager.GetCurrentClassLogger(); delegate void WhatT

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


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

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

//  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);
        }
    }
}
在本例中,我附加了一个被某个外部进程锁定的文件,写入该文件的唯一方法是重试几次,直到该进程完成为止

我当然希望看到更好的方法来处理这个特殊的模式(重试)

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

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。因此,我想我的示例仍然会对您有所帮助。

厌倦了一遍又一遍地复制/粘贴相同的代码,因此我创建了一个方法来接受必须完成的任务的委托。这是:

//  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);
        }
    }
}
在本例中,我附加了一个被某个外部进程锁定的文件,写入该文件的唯一方法是重试几次,直到该进程完成为止

我当然希望看到更好的方法来处理这个特殊的模式(重试)

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

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。因此,我想我的示例仍然会对您有所帮助。

我已经根据特定的领域需求创建了此类帮助程序,但作为一个通用的起点,请看一下Gallio的实现


我已经根据特定的领域需求创建了这样的帮助器,但是作为一个通用的起点,我们来看看Gallio的实现


哇,这是在用类固醇重试。谢谢哇,这是再次尝试使用类固醇。谢谢
睡眠
线程不是一个好主意,尤其是在GUI应用程序中。@DanAbramov同意,但这是单线程控制台应用程序,所以我想很少的
Sleep()
-ing不会有什么坏处。
睡眠
线程不是一个好主意,尤其是在GUI应用程序中。@DanAbramov同意,但这是一个单线程控制台应用程序,所以我想小
Sleep()
-ing不会有什么坏处。