Create a resilience pipeline that combines retry and timeout strategies:
using Polly;// Create an instance of builder that exposes various extensions for adding resilience strategiesResiliencePipeline pipeline = new ResiliencePipelineBuilder() .AddRetry(new RetryStrategyOptions()) // Add retry using the default options .AddTimeout(TimeSpan.FromSeconds(10)) // Add 10 seconds timeout .Build(); // Builds the resilience pipeline// Execute the pipeline asynchronouslyawait pipeline.ExecuteAsync(static async token =>{ // Your custom logic goes here var response = await httpClient.GetAsync("https://api.example.com/data", token); return response;}, cancellationToken);
The pipeline executes strategies in the order they are added. In this example, timeout wraps retry, which wraps your callback.
For ASP.NET Core and other DI-enabled applications, install Polly.Extensions:
dotnet add package Polly.Extensions
Then register your resilience pipeline:
using Microsoft.Extensions.DependencyInjection;using Polly;var services = new ServiceCollection();// Define a resilience pipeline with the name "my-pipeline"services.AddResiliencePipeline("my-pipeline", builder =>{ builder .AddRetry(new RetryStrategyOptions()) .AddTimeout(TimeSpan.FromSeconds(10));});// Build the service providervar serviceProvider = services.BuildServiceProvider();// Retrieve a ResiliencePipelineProvider that dynamically creates and caches the resilience pipelinesvar pipelineProvider = serviceProvider.GetRequiredService<ResiliencePipelineProvider<string>>();// Retrieve your resilience pipeline using the name it was registered withResiliencePipeline pipeline = pipelineProvider.GetPipeline("my-pipeline");// Alternatively, you can use keyed services to retrieve the resilience pipelinepipeline = serviceProvider.GetRequiredKeyedService<ResiliencePipeline>("my-pipeline");// Execute the pipelineawait pipeline.ExecuteAsync(static async token =>{ // Your custom logic goes here});