可能重复:
Retry a task multiple times based on user input in case of an exception in task
我正在寻找一种在TPL中实现重试逻辑的方法。我希望有一个通用函数/类,它将能够返回一个任务,该任务将执行给定的操作,如果出现异常,将重新尝试该任务,直至给定的重试计数。我试着使用ContinueWith并让回调在异常情况下创建一个新任务,但它似乎只适用于固定数量的重试。有什么建议吗?
private static void Main()
{
Task<int> taskWithRetry = CreateTaskWithRetry(DoSometing, 10);
taskWithRetry.Start();
// ...
}
private static int DoSometing()
{
throw new NotImplementedException();
}
private static Task<T> CreateTaskWithRetry<T>(Func<T> action, int retryCount)
{
}
发布于 2011-05-22 18:59:34
有什么理由跟第三方物流有什么特别的关系吗?为什么不为Func<T>
本身做一个包装呢?
public static Func<T> Retry(Func<T> original, int retryCount)
{
return () =>
{
while (true)
{
try
{
return original();
}
catch (Exception e)
{
if (retryCount == 0)
{
throw;
}
// TODO: Logging
retryCount--;
}
}
};
}
请注意,您可能希望添加一个ShouldRetry(Exception)
方法,以允许某些异常(例如取消)中止而不进行重试。
发布于 2011-05-22 19:10:25
private static Task<T> CreateTaskWithRetry<T>(Func<T> action, int retryCount)
{
Func<T> retryAction = () =>
{
int attemptNumber = 0;
do
{
try
{
attemptNumber++;
return action();
}
catch (Exception exception) // use your the exception that you need
{
// log error if needed
if (attemptNumber == retryCount)
throw;
}
}
while (attemptNumber < retryCount);
return default(T);
};
return new Task<T>(retryAction);
}
https://stackoverflow.com/questions/6090026
复制相似问题