在下面,我需要传递nextDB给Retry中的Lambda表达式:
Retry.Do(() =>
{
string nextDB = dbList.Next();
using (DataBaseProxy repo = new DataBaseProxy(nextDB))
{
return repo.DoSomething();
}
});
Run Code Online (Sandbox Code Playgroud)
我怎么做?这是我的Retry班级:
public static class Retry
{
public static void Do(
Action action,
int retryCount = 3)
{
Do<object>(() =>
{
action();
return null;
}, retryCount);
}
public static T Do<T>(
Func<T> action,
int retryCount = 3)
{
var exceptions = new List<Exception>();
for (int retry = 0; retry < retryCount; retry++)
{
try
{
return action();
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
throw new AggregateException(exceptions);
}
}
Run Code Online (Sandbox Code Playgroud)
我想你想在Action<T>这里使用.例如:
public static void Do<T>(
Action<T> action,
T param,
int retryCount = 3)
{
var exceptions = new List<Exception>();
for (int retry = 0; retry < retryCount; retry++)
{
try
{
action(param);
return;
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
throw new AggregateException(exceptions);
}
Run Code Online (Sandbox Code Playgroud)
您可以像这样调用此函数:
Do(s => {
Console.WriteLine(s);
}, "test", 3);
Run Code Online (Sandbox Code Playgroud)
根据您的评论,您似乎想要传递多个数据库并连续尝试每个数据库,直到找到有效的数据库.一个简单的选择是删除retryCount并传入您的数组.
public static void Do<T>(
Action<T> action,
IEnumerable<T> items)
{
var exceptions = new List<Exception>();
foreach(var item in items)
{
try
{
action(item);
return;
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
throw new AggregateException(exceptions);
}
Run Code Online (Sandbox Code Playgroud)
现在你称之为:
Do(s => {
Console.WriteLine(s);
}, new[] { "db1", "db2", "db3" });
Run Code Online (Sandbox Code Playgroud)