codingoutloud
2/13/2013 - 7:28 PM

Show Custom Retry Policy for Windows Azure Storage SDK.

Show Custom Retry Policy for Windows Azure Storage SDK.

// Azure Storage SDK 1.7

public static RetryPolicy TrackingRetryExponential(int maxRetryCount, TimeSpan minBackoff, TimeSpan maxBackoff, TimeSpan deltaBackoff, ILog logger)
{
   logger.InfoFormat(
      "Setting TrackingRetryExponential: maxRetryCount = {0}, minBackoff = {1}, maxBackoff = {2}, deltaBackoff = {3}",
      maxRetryCount, minBackoff, maxBackoff, deltaBackoff);

   return () => (int currentRetryCount, Exception lastException, out TimeSpan retryInterval) =>
   {
      logger.WarnFormat("#retry# blob-retry-logged TrackingRetryExponential: currentRetryCount = {0}, lastException = {1}",
                        currentRetryCount, lastException.ToString());

      var betterRandom = new System.Security.Cryptography.RNGCryptoServiceProvider();
      var randomBytes = new byte[2];
      betterRandom.GetNonZeroBytes(randomBytes);
      int randomSeed = randomBytes[0] * randomBytes[1];

      if (currentRetryCount < maxRetryCount)
      {
         var rand = new Random(randomSeed);
         var increment = (int)((Math.Pow(2, currentRetryCount) - 1) * rand.Next((int)(deltaBackoff.TotalMilliseconds * 0.8), (int)(deltaBackoff.TotalMilliseconds * 1.2)));
         var timeToSleepMsec = (int)Math.Min(minBackoff.TotalMilliseconds + increment, maxBackoff.TotalMilliseconds);

         retryInterval = TimeSpan.FromMilliseconds(timeToSleepMsec);

         return true;
      }

      retryInterval = TimeSpan.Zero;
      return false;
   };
}