如何在我的代码中正确实现Polly以避免冻结

时间:2019-07-11 13:14:15

标签: c# polly

我遇到Polly问题,导致线程冻结。 如您所见,GetData()方法将引发异常。我想做的是在DoStuff()的GetData()方法中发生异常时继续执行Dostuff1和2。但是似乎在重试了polly之后,它只是卡住了,什么也不做...

我该如何解决?

private async Task StartUp()
{
        await DoStuff());
        // await next task DoStuff1();
        // await next task DoStuff2();
}


private async Task DoStuff()
{
        var data= await Task.WhenAll(Task.Run(() => GetData()));

        // Do stuff with the data
}


private async Task<Data> GetData()
{
     //read filepaths from file.

     var tasks = filePaths
             .Select(f => polly.MyPolicy().Execute(() => ReadDataFromCSV()))
             .ToArray();
    Return await tasks;
}

private Dictionary<string, DateTime?> ReadDataFromCSV()
{

     ///Throw exception....
}

    public PolicyForGetData()
    {
        return Policy
                 .Handle<Exception>()
                 .WaitAndRetry(
                    retryCount: 2,
                    sleepDurationProvider: t => TimeSpan.FromSeconds(5),
                    onRetry: (ex, t, i, c) => {
                        Console.WriteLine(ex.Message);
                    }
                 );
    }

1 个答案:

答案 0 :(得分:1)

我认为您误会了Polly的举止。假设GetData()总是抛出,那么您的应用程序将像这样

  1. GetData()引发
  2. Polly第一次重试
  3. GetData()再次抛出
  4. Polly第二次抓到重试
  5. GetData()抛出最后一次。
  6. Polly不会捕获或重试该异常,因为您只要求它重试两次,而是将异常转义到StartUp()方法中,该方法可防止DoStuff1()DoStuff2()被叫。

例如。该程序的输出:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Policy
                 .Handle<Exception>()
                 .WaitAndRetry(
                    retryCount: 2,
                    sleepDurationProvider: t => TimeSpan.FromSeconds(5),
                    onRetry: (ex, t, i, c) => {
                        Console.WriteLine("OnRetry");
                    }
                 )
                 .Execute(() => ErrorMethod());

            Console.WriteLine("We never get here");
        }
        catch (Exception)
        {
            Console.WriteLine("Exception Handler");
        }
    }

    private static void ErrorMethod()
    {
        throw new InvalidOperationException("Badness");
    }
}

OnRetry
OnRetry
Exception Handler