Zum Fußzeileninhalt springen
.NET HILFE

.NET Core Polly (Wie es für Entwickler funktioniert)

Polly is a .NET resilience strategies and transient fault handling library, allowing developers to express resilience policies such as Retry policy, Circuit Breakers, Timeout, Bulkhead Isolation policy, and Fallback. Polly targets ASP.NET Core, making it a vital tool for .NET Core resilience. Polly is thread-safe and supports handling multiple concurrent requests with successful responses.

This tutorial will provide more details about the transient fault handling .NET library, Polly, and how to use it with IronPDF in an ASP.NET Core application. We'll take a deep dive into each aspect of Polly, explain the mechanics of the circuit breaker pattern, discuss bulkhead isolation and timeouts, and show how to handle specific exceptions or failing services with failure responses in a controlled, thread-safe manner.

Polly Policies

Transient faults often occur when your application tries to connect with a web service through an HTTP request, database, or other external resources. These faults, like network failures, temporary connectivity issues, or timeouts, are brief and typically correct themselves after a short time.

Polly manages these transient faults by applying different strategies and expressing policies like Retry Policy, advanced Circuit Breaker Policy, Timeout Policy, Fallback Policy, and Bulkhead Isolation Policy.

Retry Policy

Retry Policy automatically retries failed concurrent requests using retry logic. It can be configured to retry forever or do automatic retries for a certain number of times, and it can wait a set time interval between retries or use an exponential back-off.

Circuit Breaker

The Circuit Breaker policy lets your system support a cancellation token for trying a particular service after a pre-configured threshold of failed requests. The Circuit Breaker strategy is analogous to chaos engineering or a ship closing watertight doors to localize damage: one fault won't sink the whole ship.

Timeout Policy

Timeout policy enforces a maximum time that a particular piece of .NET resilience code can execute. It comes in two flavors: optimistic timeout and pessimistic timeout.

Fallback Policy

Fallback policy is used to provide a substitute value or behavior in the event of a failure. This policy can be useful when a failing service should not halt the entire process.

Bulkhead Isolation

Bulkhead isolation is used to limit how many concurrent requests can be made to a specific operation, thereby limiting the potential for socket exhaustion and maintaining a controlled number of execution slots.

Cache Policy

The cache policy caches the successful response of an execution so that if the same execution is invoked again, Polly can return the distributed cache value.

Policy Wrap

Allows us to wrap multiple policies together, so they can work as a single unit.

Create and Configure Policies

Retry Policy

A retry policy is simple: when a specific exception or a fault occurs, Polly will try to execute the underlying delegate again. You can define how many times to retry, the time interval between retries, or use an exponential back-off strategy else it will retry forever. Here's an example:

// Retry policy for handling HttpRequestException with exponential back-off
var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), 
    (exception, timeSpan, retryCount, context) =>
    {
        // This is the OnRetry delegate, where you can log or monitor failed requests
        Console.WriteLine($"Retry {retryCount} after {timeSpan}. Exception: {exception.Message}");
    });
// Retry policy for handling HttpRequestException with exponential back-off
var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), 
    (exception, timeSpan, retryCount, context) =>
    {
        // This is the OnRetry delegate, where you can log or monitor failed requests
        Console.WriteLine($"Retry {retryCount} after {timeSpan}. Exception: {exception.Message}");
    });
' Retry policy for handling HttpRequestException with exponential back-off
Dim retryPolicy = Policy.Handle(Of HttpRequestException)().WaitAndRetryAsync(3, Function(retryAttempt) TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), Sub(exception, timeSpan, retryCount, context)
	Console.WriteLine($"Retry {retryCount} after {timeSpan}. Exception: {exception.Message}")
End Sub)
$vbLabelText   $csharpLabel

Circuit Breaker Policy

The Circuit Breaker policy lets the Polly library monitor for faults, and if the number of faults exceeds a configured threshold within a specified period, the circuit is "broken," and further requests are blocked for a specified time. This is called the 'open' state. After this time, the circuit enters a 'half-open' state, where it allows some traffic to check the health of the particular service. If these requests are successful and no faults occur, the circuit closes; otherwise, it opens again.

// Circuit breaker policy to handle failing requests with open and half-open states
var circuitBreakerPolicy = Policy
    .Handle<HttpRequestException>()
    .CircuitBreakerAsync(5, TimeSpan.FromMinutes(1));
// Circuit breaker policy to handle failing requests with open and half-open states
var circuitBreakerPolicy = Policy
    .Handle<HttpRequestException>()
    .CircuitBreakerAsync(5, TimeSpan.FromMinutes(1));
' Circuit breaker policy to handle failing requests with open and half-open states
Dim circuitBreakerPolicy = Policy.Handle(Of HttpRequestException)().CircuitBreakerAsync(5, TimeSpan.FromMinutes(1))
$vbLabelText   $csharpLabel

Timeout Policy

Timeout policies handle scenarios where a service isn't responding within a reasonable timeframe. Polly offers two types of timeouts: Optimistic and Pessimistic. An optimistic timeout works on a separate thread and cancels the underlying operation via a CancellationToken. A pessimistic timeout blocks the parent thread until the operation completes or the timeout period elapses.

// Timeout policy with a 30-second optimistic timeout
var timeoutPolicy = Policy.TimeoutAsync(30); // 30 seconds
// Timeout policy with a 30-second optimistic timeout
var timeoutPolicy = Policy.TimeoutAsync(30); // 30 seconds
' Timeout policy with a 30-second optimistic timeout
Dim timeoutPolicy = Policy.TimeoutAsync(30) ' 30 seconds
$vbLabelText   $csharpLabel

Bulkhead Isolation

Bulkhead Isolation is used to limit the number of concurrent actions against a particular service. It provides a way to isolate faults and prevent them from cascading. It also limits the load we place on our dependencies.

// Bulkhead isolation policy to limit concurrency and queue length
var bulkheadIsolationPolicy = Policy.BulkheadAsync(10, 20); // 10 concurrent actions, 20 queue slots
// Bulkhead isolation policy to limit concurrency and queue length
var bulkheadIsolationPolicy = Policy.BulkheadAsync(10, 20); // 10 concurrent actions, 20 queue slots
' Bulkhead isolation policy to limit concurrency and queue length
Dim bulkheadIsolationPolicy = Policy.BulkheadAsync(10, 20) ' 10 concurrent actions, 20 queue slots
$vbLabelText   $csharpLabel

Fallback Policy

Fallback policies are useful when you need to provide a default behavior or substitute value when all else fails.

// Fallback policy to provide a default result on failure
var fallbackPolicy = Policy
    .Handle<Exception>()
    .FallbackAsync<FallbackResult>(
        FallbackResult.SomethingWentWrong, 
        (exception, context) => 
        {
            Console.WriteLine($"Fallback triggered due to: {exception.Message}");
            return Task.CompletedTask;
        });
// Fallback policy to provide a default result on failure
var fallbackPolicy = Policy
    .Handle<Exception>()
    .FallbackAsync<FallbackResult>(
        FallbackResult.SomethingWentWrong, 
        (exception, context) => 
        {
            Console.WriteLine($"Fallback triggered due to: {exception.Message}");
            return Task.CompletedTask;
        });
' Fallback policy to provide a default result on failure
Dim fallbackPolicy = Policy.Handle(Of Exception)().FallbackAsync(Of FallbackResult)(FallbackResult.SomethingWentWrong, Function(exception, context)
			Console.WriteLine($"Fallback triggered due to: {exception.Message}")
			Return Task.CompletedTask
End Function)
$vbLabelText   $csharpLabel

Wrapping the Policies

Multiple policies can be combined flexibly using a PolicyWrap:

// Combining multiple policies using PolicyWrap
var policyWrap = Policy.WrapAsync(fallbackPolicy, retryPolicy, circuitBreakerPolicy, timeoutPolicy, bulkheadIsolationPolicy);
// Combining multiple policies using PolicyWrap
var policyWrap = Policy.WrapAsync(fallbackPolicy, retryPolicy, circuitBreakerPolicy, timeoutPolicy, bulkheadIsolationPolicy);
' Combining multiple policies using PolicyWrap
Dim policyWrap = Policy.WrapAsync(fallbackPolicy, retryPolicy, circuitBreakerPolicy, timeoutPolicy, bulkheadIsolationPolicy)
$vbLabelText   $csharpLabel

Getting Started

To begin using Polly with IronPDF, make sure you have Visual Studio installed and create a new Console Application project in .NET Core. Open the NuGet Package Manager Console in Visual Studio and install the Polly and IronPDF packages:

Install-Package Polly
Install-Package IronPdf

Using Polly with IronPDF Converting a URL to PDF

A prominent feature of IronPDF is its HTML to PDF capability, ensuring layouts and styles are intact. This function turns web content into PDFs, which is perfect for reports, invoices, and documentation. It supports converting HTML files, URLs, and HTML strings to PDFs.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

Let's walk through an example of using Polly with IronPDF to convert a URL to PDF. Assume we have a web service that occasionally fails due to transient faults, and we want to handle those failures gracefully using Polly.

First, let's import the necessary namespaces in our Program.cs file:

using System;
using System.Threading.Tasks;
using Polly;
using Polly.Wrap;
using IronPdf;
using System;
using System.Threading.Tasks;
using Polly;
using Polly.Wrap;
using IronPdf;
Imports System
Imports System.Threading.Tasks
Imports Polly
Imports Polly.Wrap
Imports IronPdf
$vbLabelText   $csharpLabel

Next, we'll define our policies. In this example, we'll use a combination of retry and circuit breaker policies to handle failures:

// Retry policy with exponential backoff
var retryPolicy = Policy
    .Handle<Exception>()
    .WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(2 * i));

// Circuit breaker policy to block requests after consecutive failures
var circuitBreakerPolicy = Policy
    .Handle<Exception>()
    .CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));
// Retry policy with exponential backoff
var retryPolicy = Policy
    .Handle<Exception>()
    .WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(2 * i));

// Circuit breaker policy to block requests after consecutive failures
var circuitBreakerPolicy = Policy
    .Handle<Exception>()
    .CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));
' Retry policy with exponential backoff
Dim retryPolicy = Policy.Handle(Of Exception)().WaitAndRetryAsync(3, Function(i) TimeSpan.FromSeconds(2 * i))

' Circuit breaker policy to block requests after consecutive failures
Dim circuitBreakerPolicy = Policy.Handle(Of Exception)().CircuitBreakerAsync(2, TimeSpan.FromSeconds(30))
$vbLabelText   $csharpLabel

The retryPolicy will retry the failed request up to three times with an exponential backoff strategy, waiting 2 seconds, 4 seconds, and 8 seconds between retries. The circuitBreakerPolicy will open the circuit if two consecutive failures occur within a 30-second time interval.

Now, let's define our IronPDF code to convert a URL to a PDF:

var htmlToPdf = new ChromePdfRenderer();
var pdfBytes = await retryPolicy
    .WrapAsync(circuitBreakerPolicy)
    .ExecuteAsync(async () =>
    {
        Console.WriteLine("Attempting to convert URL to PDF...");
        var result = await htmlToPdf.RenderUrlAsPdfAsync("https://example.com");
        Console.WriteLine("Conversion successful!");
        return result;
    });

pdfBytes.SaveAs("output.pdf");
var htmlToPdf = new ChromePdfRenderer();
var pdfBytes = await retryPolicy
    .WrapAsync(circuitBreakerPolicy)
    .ExecuteAsync(async () =>
    {
        Console.WriteLine("Attempting to convert URL to PDF...");
        var result = await htmlToPdf.RenderUrlAsPdfAsync("https://example.com");
        Console.WriteLine("Conversion successful!");
        return result;
    });

pdfBytes.SaveAs("output.pdf");
Dim htmlToPdf = New ChromePdfRenderer()
Dim pdfBytes = Await retryPolicy.WrapAsync(circuitBreakerPolicy).ExecuteAsync(Async Function()
		Console.WriteLine("Attempting to convert URL to PDF...")
		Dim result = Await htmlToPdf.RenderUrlAsPdfAsync("https://example.com")
		Console.WriteLine("Conversion successful!")
		Return result
End Function)

pdfBytes.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

In the above example code, we wrap our retryPolicy and circuitBreakerPolicy using the WrapAsync method. This allows us to apply multiple policies to new requests sequentially. The ExecuteAsync method executes the provided delegate, which in this code is the RenderUrlAsPdfAsync method from IronPDF.

By applying Polly policies, we ensure that our code is resilient to transient faults. If a request fails, Polly will automatically retry it according to the retry policy. If the number of consecutive failures crosses the pre-configured threshold, the circuit breaker policy will open the circuit, preventing further requests for a specified duration.

Test Cases for Polly Policies

To test the effectiveness of our Polly policies, let's simulate some failed requests. Modify the URL to a non-existent endpoint and add a few test cases:

var testUrls = new[]
{
    "https://ironpdf.com",
    "https://notexistingdomain.com/",
    "http://httpbin.org/delay/120"
};

foreach (var url in testUrls)
{
    try
    {
        var pdfBytes = await retryPolicy
            .WrapAsync(circuitBreakerPolicy)
            .ExecuteAsync(() => htmlToPdf.RenderUrlAsPdfAsync(url));

        pdfBytes.SaveAs($"{Guid.NewGuid()}.pdf");
        Console.WriteLine($"Successfully converted {url} to PDF.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to convert {url} to PDF: {ex.Message}");
    }
}
var testUrls = new[]
{
    "https://ironpdf.com",
    "https://notexistingdomain.com/",
    "http://httpbin.org/delay/120"
};

foreach (var url in testUrls)
{
    try
    {
        var pdfBytes = await retryPolicy
            .WrapAsync(circuitBreakerPolicy)
            .ExecuteAsync(() => htmlToPdf.RenderUrlAsPdfAsync(url));

        pdfBytes.SaveAs($"{Guid.NewGuid()}.pdf");
        Console.WriteLine($"Successfully converted {url} to PDF.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to convert {url} to PDF: {ex.Message}");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

In the above code, we iterate over a set of test URLs and attempt to convert each of them to PDF. If a request fails, the exception will be caught, and an appropriate message will be displayed in the console.

.NET Core Polly (How It Works For Developers): Figure 1 - URL to PDF Output

Conclusion

Polly is a powerful and flexible library for implementing resilience and transient fault handling in .NET Core applications. By combining policies like retry and circuit breaker, developers can build robust and fault-tolerant systems that gracefully handle failures.

In this tutorial, we explored how to use Polly with IronPDF to convert a URL to PDF. We learned how to define and apply Polly policies, including retry and circuit breaker. We also tested our policies with different URLs. We can also do it for converting HTML to PDF.

IronPDF offers a free trial, and licenses start at competitive pricing, allowing you to leverage its capabilities in your projects.

Häufig gestellte Fragen

Was ist Polly und wie verbessert es die Resilienz von .NET Core?

Polly ist eine .NET-Bibliothek, die für Resilienz und die Handhabung von temporären Fehlern entwickelt wurde, insbesondere für ASP.NET Core-Anwendungen. Sie verbessert die Resilienz, indem sie Strategien wie Wiederholung, Schutzschalter, Timeout, Schott-Isolation und Fallback bietet, um robuste und fehlertolerante Systeme zu gewährleisten.

Wie kann ich Polly verwenden, um eine Wiederholungsrichtlinie in .NET Core umzusetzen?

In .NET Core können Sie Polly verwenden, um eine Wiederholungsrichtlinie zu implementieren, indem Sie es konfigurieren, fehlgeschlagene Anfragen automatisch zu wiederholen. Dies kann durch Festlegen der Anzahl der Wiederholungen und des Zeitintervalls zwischen den Versuchen geschehen, was ein effektives Management von temporären Fehlern ermöglicht.

Wie verhindert die Schutzschalter-Richtlinie Kaskadenfehler in .NET-Anwendungen?

Die Schutzschalter-Richtlinie in Polly verhindert Kaskadenfehler, indem sie Fehler überwacht und den Stromkreis öffnet, um Anfragen zu blockieren, wenn ein Fehlerschwellenwert erreicht wird. Dadurch werden weitere Anfragen gestoppt, bis der Stromkreis zurückgesetzt wird, sodass sich das System erholen kann, bevor es neue Anfragen annimmt.

Welche Rolle spielt die Schott-Isolation bei der Verwaltung von Ressourcenauslastung?

Die Schott-Isolation in Polly begrenzt die Anzahl gleichzeitiger Anfragen an einen Dienst und verhindert Ressourcenauslastung, indem sie Ausführungsslots kontrolliert. Diese Richtlinie hilft, Fehler einzudämmen und sorgt für ein effizientes Ressourcenmanagement innerhalb einer .NET Core-Anwendung.

Wie kann die Timeout-Richtlinie von Polly die Reaktionsfähigkeit meiner Anwendung verbessern?

Die Timeout-Richtlinie von Polly erzwingt eine maximale Ausführungszeit für Operationen, was bei der Bewältigung von Szenarien hilft, in denen Dienste nicht sofort reagieren. Durch Festlegung von optimistischen oder pessimistischen Zeitlimits können Entwickler sicherstellen, dass ihre Anwendungen reaktionsfähig bleiben.

Kann Polly verwendet werden, um die Zuverlässigkeit der URL-zu-PDF-Konvertierung zu verbessern?

Ja, Polly kann die Zuverlässigkeit der URL-zu-PDF-Konvertierung verbessern, indem es seine Wiederholungs- und Schutzschalter-Richtlinien mit PDF-Generierungswerkzeugen integriert. Dies stellt sicher, dass Konversionsprozesse gegenüber temporären Fehlern widerstandsfähig sind und die Zuverlässigkeit erhalten bleibt.

Wie stellt eine Fallback-Richtlinie in Polly einen anmutigen Dienstabbau sicher?

Eine Fallback-Richtlinie in Polly bietet alternative Antworten oder Verhaltensweisen, wenn ein Dienst ausfällt. Dies hilft sicherzustellen, dass ein Fehler nicht die gesamte Anwendung anhält, sondern einen anmutigen Abbau und fortlaufenden Betrieb ermöglicht.

Wie kombiniert man mehrere Polly-Richtlinien in einer .NET-Anwendung?

In einer .NET-Anwendung können mehrere Polly-Richtlinien mit Policy Wraps kombiniert werden. Dadurch können Entwickler verschiedene Resilienzstrategien zusammen ausführen und eine umfassendere und flexiblere Fehlermanagementstrategie ermöglichen.

Wie kann die Integration von Polly mit IronPDF temporäre Fehler in der PDF-Generierung behandeln?

Durch die Integration von Polly mit IronPDF können Entwickler temporäre Fehler während der PDF-Generierung durch Richtlinien wie Wiederholung und Schutzschalter behandeln. Diese Integration sorgt für eine stabile und zuverlässige PDF-Generierung trotz gelegentlicher Dienstunterbrechungen.

Was sind einige häufige Strategien zur Fehlerbehebung bei der Verwendung von Polly mit .NET Core?

Häufige Strategien zur Fehlerbehebung umfassen die Überprüfung der Richtlinienkonfigurationen, wie Wiederholungsintervalle und Schutzschalterschwellen, und das Testen der Richtlinien mit unterschiedlichen Szenarien, um einen ordnungsgemäßen Umgang mit Fehlern und Systemresilienz sicherzustellen.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen