问题描述
我在寻找一种方式来实现重试逻辑TPL。我想有一个泛型函数/类,将能够返回任务将执行一个给定的动作,并在发生异常将重试任务,直到给定的重试次数。我试着玩ContinueWith并在异常的回调函数创建一个新的任务,但它似乎将仅适用于重试的固定金额。有什么建议?
私有静态无效的主要()
{
任务< INT> taskWithRetry = CreateTaskWithRetry(DoSometing,10);
taskWithRetry.Start();
// ...
}
私有静态诠释DoSometing()
{
抛出新的NotImplementedException();
}
私有静态任务< T> CreateTaskWithRetry< T>(Func键< T>的行动,诠释retryCount)
{
}
任何理由做什么特别要做的第三方物流?为什么不只是做一个包装 Func键< T>
本身
公共静态函数功能< T>重试(Func键< T>原来,INT retryCount)
{
返程()=>
{
而(真)
{
尝试
{
返回原来的();
}
赶上(例外五)
{
如果(retryCount == 0)
{
扔;
}
// TODO:记录
retryCount--;
}
}
};
}
请注意,您可能需要添加一个 ShouldRetry(异常)
法允许某些例外(如取消)退出而不重试。
I'm looking for a way to implement retry logic in TPL. I would like to have a generic function/class that will be able to return a Task which will execute a given action and in case of an exception will retry the task, up to the given retry count. I tried playing with ContinueWith and have the callback create a new task in case of an exception, but it seems that it will only work for fixed amount of retries. Any suggestions?
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)
{
}
Any reason to do anything special to do with the TPL? Why not just make a wrapper for Func<T>
itself?
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--;
}
}
};
}
Note that you may want to add a ShouldRetry(Exception)
method to allow certain exceptions (e.g. cancellation) abort without the retry.
这篇关于如何实现与任务并行库(TPL)重试逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!