次の方法で共有


Specifying Retry Strategies in Code

Retired Content

This content and the technology described is outdated and is no longer being maintained. For more information, see Transient Fault Handling.

patterns & practices Developer Center

On this page:
Usage Notes

You do not need to define your retry strategies in a configuration file. In scenarios, with a small number of operations that require retry logic, it may be quicker to define the all of the retry policy in code.

The following code sample shows how you can define your retry strategy, create a retry policy, and use the retry policy to invoke a method that may fail because of a transient fault.

using Microsoft.Practices.TransientFaultHandling;
using Microsoft.Practices.EnterpriseLibrary.WindowsAzure.TransientFaultHandling;
...
// Define your retry strategy: retry 5 times, starting 1 second apart
// and adding 2 seconds to the interval each retry.
var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), 
  TimeSpan.FromSeconds(2));

// Define your retry policy using the retry strategy and the Azure storage
// transient fault detection strategy.
var retryPolicy =
  new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy);

// Receive notifications about retries.
retryPolicy.Retrying += (sender, args) =>
    {
        // Log details of the retry.
        var msg = String.Format("Retry - Count:{0}, Delay:{1}, Exception:{2}",
            args.CurrentRetryCount, args.Delay, args.LastException);
        Trace.WriteLine(msg, "Information");
    };

try
{
  // Do some work that may result in a transient fault.
  retryPolicy.ExecuteAction(
    () =>
    {
        // Call a method that uses Azure storage and which may
        // throw a transient exception.
        this.queue.CreateIfNotExist();
    });
}
catch (Exception)
{
  // All the retries failed.
}

This example shows how to use the Retrying event to receive notifications in your code when a retry occurs.

Note

The CurrentRetryCount value is the number of retry attempts after the initial attempt to invoke the action.

Usage Notes

Next Topic | Previous Topic | Home

Last built: June 7, 2012