如何使用任务并行库(TPL)实现重试逻辑

可能重复:
如果任务中发生exception,则根据用户输入多次重试任务

我正在寻找一种在TPL中实现重试逻辑的方法。 我想有一个generics函数/类,它将能够返回一个将执行给定操作的Task,并且在exception的情况下将重试该任务,直到给定的重试计数。 我尝试使用ContinueWith进行播放,并且在出现exception时让回调创建一个新任务,但它似乎只适用于固定数量的重试。 有什么建议?

private static void Main() { Task taskWithRetry = CreateTaskWithRetry(DoSometing, 10); taskWithRetry.Start(); // ... } private static int DoSometing() { throw new NotImplementedException(); } private static Task CreateTaskWithRetry(Func action, int retryCount) { } 

有什么理由与TPL有什么特别之处吗? 为什么不为Func本身制作一个包装器呢?

 public static Func Retry(Func original, int retryCount) { return () => { while (true) { try { return original(); } catch (Exception e) { if (retryCount == 0) { throw; } // TODO: Logging retryCount--; } } }; } 

请注意,您可能希望添加一个ShouldRetry(Exception)方法,以允许某些exception(例如,取消)在不重试的情况下中止。

 private static Task CreateTaskWithRetry(Func action, int retryCount) { Func 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(retryAction); }