开发者

How to implement retry logic with Task Parallel Library(TPL) [duplicate]

开发者 https://www.devze.com 2023-03-07 11:28 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: Retry a task multiple times based on user input in case of an exception in task
This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Retry a task multiple times based on user input in case of an exception in task

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 NotImplementedE开发者_如何学运维xception();
    }

    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.


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消