跟进这里的问题: Cleanest way to write retry logic?
在答案中,定义并使用了一个重试函数的通用类:
Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));
您将如何实现通用重试,构造函数也可以在其中抛出异常?
所以我不只是想重试:
SomeFunctionThatCanFail()
我想以通用方式重试以下 block :
SomeClass sc = new SomeClass();
sc.SomeFunctionThatCanFail();
最佳答案
where the constructor can throw also?
通常这是个坏主意。我建议查看工厂模式:
public class SomeClass
{
private SomeClass()
{
}
public static SomeClass GetInstance()
{
// Throw Exception here, not in constructor
}
public void SomeFunctionThatCanFail()
{
}
}
现在您可以:
Retry.Do(() =>
SomeClass.GetInstance().SomeFunctionThatCanFail(),
TimeSpan.FromSeconds(1));
关于c# - 构造函数可以抛出代码的通用重试逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41271796/