构造函数可以抛出代码的通用重试逻辑
Generic Retry Logic for code where Constructor Can Throw
跟进这里的问题:
Cleanest way to write retry logic?
在答案中,定义并使用了一个通用的 class 来重试函数:
Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));
您将如何实现通用重试,构造函数也可以在其中抛出?
所以我不想重试:
SomeFunctionThatCanFail()
我想以通用方式重试以下块:
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));
我没有意识到我可以将一段代码放入 Lambda 表达式中。这正是我想要的:
Retry.Do(() => { using (DataBaseProxy db = new DataBaseProxy(dbList.Next())) { .DoSomething(); } }, new TimeSpan(0));
跟进这里的问题: Cleanest way to write retry logic?
在答案中,定义并使用了一个通用的 class 来重试函数:
Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));
您将如何实现通用重试,构造函数也可以在其中抛出?
所以我不想重试:
SomeFunctionThatCanFail()
我想以通用方式重试以下块:
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));
我没有意识到我可以将一段代码放入 Lambda 表达式中。这正是我想要的:
Retry.Do(() => { using (DataBaseProxy db = new DataBaseProxy(dbList.Next())) { .DoSomething(); } }, new TimeSpan(0));