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

Amo*_*mos 11 .net c# task-parallel-library

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

我正在寻找一种在TPL中实现重试逻辑的方法.我想有一个泛型函数/类,它将能够返回一个将执行给定操作的Task,并且在异常的情况下将重试该任务,直到给定的重试计数.我尝试使用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)
    {

    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 9

有什么理由与TPL做任何特别的事吗?为什么不为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--;
            }
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

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