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

由网友(未来的你身下的她)分享简介:可能重复: Retry基于用户输入一个任务多次的情况下在任务异常的的我在寻找一种方式来实现重试逻辑TPL。我想有一个泛型函数/类,将能够返回任务将执行一个给定的动作,并在发生异常将重试任务,直到给定的重试次数。我试着玩ContinueWith并在异常的回调函数创建一个新的任务,但它似乎将仅适用于重试的固定金额。有什么...

可能重复:   Retry基于用户输入一个任务多次的情况下在任务异常的的

我在寻找一种方式来实现重试逻辑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(异常)法允许某些例外(如取消)退出而不重试。

如何在不需要特殊库或类的情况下实现C代码并行性

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 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.

阅读全文

相关推荐

最新文章