Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.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#版本的优雅Python可重用等待?_C#_Python_Wait - Fatal编程技术网

是否有一个类似于我的C#版本的优雅Python可重用等待?

是否有一个类似于我的C#版本的优雅Python可重用等待?,c#,python,wait,C#,Python,Wait,我在找这样的东西: public static class Retry { public static void Do( Action action, TimeSpan retryInterval, int retryCount = 3) { Do<object>(() => { action(); return null; }, ret

我在找这样的东西:

public static class Retry
{
   public static void Do(
       Action action,
       TimeSpan retryInterval,
       int retryCount = 3)
   {
       Do<object>(() => 
       {
           action();
           return null;
       }, retryInterval, retryCount);
   }

   public static T Do<T>(
       Func<T> action, 
       TimeSpan retryInterval,
       int retryCount = 3)
   {
       var exceptions = new List<Exception>();

       for (int retry = 0; retry < retryCount; retry++)
       {
          try
          { 
              if (retry > 0)
                  Thread.Sleep(retryInterval);
              return action();
          }
          catch (Exception ex)
          { 
              exceptions.Add(ex);
          }
       }

       throw new AggregateException(exceptions);
   }
}
公共静态类重试
{
公共静态无效吗(
行动行动,
TimeSpan retryInterval,
int retryCount=3)
{
做(()=>
{
动作();
返回null;
},retryInterval,retryCount);
}
公共静态不做(
Func action,
TimeSpan retryInterval,
int retryCount=3)
{
var exceptions=新列表();
for(int retry=0;retry0)
睡眠(重试区间);
返回动作();
}
捕获(例外情况除外)
{ 
例外情况。添加(ex);
}
}
抛出新的AggregateException(异常);
}
}
从本帖:


我是Python方面的一个相当不错的人,我知道如果有人有一些技巧,这会非常好。这适用于经常出现但很少优雅处理的测试代码。

您可以这样做,添加异常处理和其他提示:

def retry_fn(retry_count, delay, fn, *args, *kwargs):
    retry = True
    while retry and retry_count:
        retry_count -= 1
        success, results = fn(*args, **kwargs):
        if success or not retry_count:
            return results
        time.sleep(delay)
这个包可能正是你想要的。