1

I've been working with a remote web service over an unreliably and/or slow VPN that brought to light a point of failure in my code when I call a web service I will get timeout exceptions. I did a little googling and found Polly and seemed to be exactly what I needed, but I'm still getting an unhandled TimeoutException and would like to know what I'm doing wrong and how to update the code so that the TimeoutException is handled, preferably using Polly.

        var networkPolicy = Policy
              .Handle<TimeoutException>()
              .Or<CommunicationException>()
              .WaitAndRetry(
                   5,
                   retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                   (exception, timeSpan, context) =>
                   {
                        System.Diagnostics.Debug.WriteLine("Exception being retried" + exception );
                   });
        // The following line is giving me the exception.
        response = networkPolicy.Execute(() => soapClient.WebServiceFunction(request));

I'd also like to know if it is best practice to define the policy as a static readonly variable?

4

1 回答 1

1

Polly 的工作原理是在发生错误时重复操作,但只有一定次数。如果错误发生多次,Polly 会抛出它。

如果你想重复它直到它没有被抛出 expetion 然后使用 RetryForever。

通常我使用 Polly 和 try catch - 就像这里:

    try
    {
        return
            await
            Policy.Handle<MongoConnectionException>()
                  .RetryAsync(3,
                      (exception, i) =>
                          {
                              logger.Warn(exception,
                                  string.Format("Mongo Connection Exception - Retry Count : {0}", i));
                          })
                  .ExecuteAsync(async () => await operation());
    }
    catch (MongoConnectionException ex)
    {
        logger.Error(ex);
        return null;
    }
于 2015-10-14T20:55:11.307 回答