Polly Retry(開発者向けの動作方法)
一時的な障害、タイムアウト、および例外を上手に処理することは、堅牢で回復力のあるアプリケーション構築において重要です。 Pollyは、復元力と一時的な障害処理機能を提供する人気のある.NETライブラリです。 その多くの機能の中で、"リトライ"は最も広く使用されているポリシーの一つです。
この記事では、PollyのC#におけるリトライポリシーを掘り下げて、その使用方法、設定オプションを探り、実用的なコード例を提供します。 また、Pollyリトライ試行とともにPDF生成のためのIronPDFライブラリを使用して、フォームリクエスト結果のPDFを生成します。
Pollyリトライとは?
Pollyリトライは、エラーや一時的な障害により失敗する可能性のある操作を自動的に再試行できるようにするPollyライブラリによって提供されるポリシーです。 一時的な障害は、ネットワークの不具合、サービスの利用不可、または他の一時的な問題によって発生する一時的なエラーです。
Pollyのリトライポリシーでは、操作を再試行するためのルールを定義できます。これには、再試行の最大回数、複数の再試行の間の遅延、および失敗したリクエストを再試行する条件が含まれます。これにより、一時的な障害からクラッシュしたり、エンドユーザーに影響を与えたりすることなく回復できる堅牢なアプリケーションの構築が可能になります。
Pollyリトライの始め方
コード例に入る前に、C#プロジェクトにPollyをインストールして設定する方法の基本を設定しましょう。
Pollyのインストール
NuGetパッケージ マネージャー コンソールを使用して、以下のコマンドでPollyをインストールできます。
.NET CLIを通じて:
Pollyのusingステートメントを追加
C#ファイルにPolly名前空間を含めてください。
using Polly;Imports PollyImports Polly基本的なリトライポリシーの例
リモートサービスからデータを取得する操作を再試行するシンプルな例から始めましょう。最大3回の再試行と再試行間の固定タイムアウト遅延2秒でリトライポリシーを設定します。
using System;
using System.Net.Http;
using Polly;
namespace PollyRetryExample
{
public class Program
{
public static void Main(string[] args)
{
// Define a retry policy that handles HttpRequestException with a maximum of 3 retries
var retryPolicy = Policy
.Handle<HttpRequestException>() // Specify the exception type to handle
.WaitAndRetry(
3, // Max retry attempts
retryAttempt => TimeSpan.FromSeconds(2), // Fixed retry delay
(exception, timeSpan, retryCount, context) =>
{
Console.WriteLine("Retry {0} due to {1}", retryCount, exception.Message);
});
try
{
// Execute the action within the context of the retry policy
retryPolicy.Execute(() =>
{
FetchDataFromRemoteService();
});
}
catch (Exception ex)
{
Console.WriteLine("Failed after 3 retries: {0}", ex.Message);
}
}
// Simulate fetching data that throws HttpRequestException
public static void FetchDataFromRemoteService()
{
throw new HttpRequestException("Failed to fetch data from remote service");
}
}
}using System;
using System.Net.Http;
using Polly;
namespace PollyRetryExample
{
public class Program
{
public static void Main(string[] args)
{
// Define a retry policy that handles HttpRequestException with a maximum of 3 retries
var retryPolicy = Policy
.Handle<HttpRequestException>() // Specify the exception type to handle
.WaitAndRetry(
3, // Max retry attempts
retryAttempt => TimeSpan.FromSeconds(2), // Fixed retry delay
(exception, timeSpan, retryCount, context) =>
{
Console.WriteLine("Retry {0} due to {1}", retryCount, exception.Message);
});
try
{
// Execute the action within the context of the retry policy
retryPolicy.Execute(() =>
{
FetchDataFromRemoteService();
});
}
catch (Exception ex)
{
Console.WriteLine("Failed after 3 retries: {0}", ex.Message);
}
}
// Simulate fetching data that throws HttpRequestException
public static void FetchDataFromRemoteService()
{
throw new HttpRequestException("Failed to fetch data from remote service");
}
}
}Imports System
Imports System.Net.Http
Imports Polly
Namespace PollyRetryExample
Public Class Program
Public Shared Sub Main(ByVal args() As String)
' Define a retry policy that handles HttpRequestException with a maximum of 3 retries
Dim retryPolicy = Policy.Handle(Of HttpRequestException)().WaitAndRetry(3, Function(retryAttempt) TimeSpan.FromSeconds(2), Sub(exception, timeSpan, retryCount, context)
Console.WriteLine("Retry {0} due to {1}", retryCount, exception.Message)
End Sub)
Try
' Execute the action within the context of the retry policy
retryPolicy.Execute(Sub()
FetchDataFromRemoteService()
End Sub)
Catch ex As Exception
Console.WriteLine("Failed after 3 retries: {0}", ex.Message)
End Try
End Sub
' Simulate fetching data that throws HttpRequestException
Public Shared Sub FetchDataFromRemoteService()
Throw New HttpRequestException("Failed to fetch data from remote service")
End Sub
End Class
End NamespaceImports System
Imports System.Net.Http
Imports Polly
Namespace PollyRetryExample
Public Class Program
Public Shared Sub Main(ByVal args() As String)
' Define a retry policy that handles HttpRequestException with a maximum of 3 retries
Dim retryPolicy = Policy.Handle(Of HttpRequestException)().WaitAndRetry(3, Function(retryAttempt) TimeSpan.FromSeconds(2), Sub(exception, timeSpan, retryCount, context)
Console.WriteLine("Retry {0} due to {1}", retryCount, exception.Message)
End Sub)
Try
' Execute the action within the context of the retry policy
retryPolicy.Execute(Sub()
FetchDataFromRemoteService()
End Sub)
Catch ex As Exception
Console.WriteLine("Failed after 3 retries: {0}", ex.Message)
End Try
End Sub
' Simulate fetching data that throws HttpRequestException
Public Shared Sub FetchDataFromRemoteService()
Throw New HttpRequestException("Failed to fetch data from remote service")
End Sub
End Class
End Namespaceこの例では:
Handle<HttpRequestException>()は、HttpRequestExceptionを処理し、それが発生した場合に操作をリトライすることを指定します。WaitAndRetry()は、3回のリトライとリトライ間に2秒の固定遅延があるリトライポリシーを設定します(指定された最大期間)。onRetryデリゲートは、リトライが発生したときにメッセージをログに記録します。

高度なリトライポリシー設定
指数バックオフ
指数バックオフは、要求と再試行の間の遅延が指数関数的に増加する人気のあるリトライ戦略です。 Polly は、WaitAndRetry() を使用して指数バックオフを実装する便利な方法を提供します。
var retryPolicy = Policy
.Handle<HttpRequestException>()
.WaitAndRetry(
retryCount: 3, // Max retry attempts
sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)), // Exponential delay
onRetry: (exception, timeSpan, retryCount, context) =>
{
Console.WriteLine($"Retry {retryCount} due to {exception.Message}");
});var retryPolicy = Policy
.Handle<HttpRequestException>()
.WaitAndRetry(
retryCount: 3, // Max retry attempts
sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)), // Exponential delay
onRetry: (exception, timeSpan, retryCount, context) =>
{
Console.WriteLine($"Retry {retryCount} due to {exception.Message}");
});Dim retryPolicy = Policy.Handle(Of HttpRequestException)().WaitAndRetry(retryCount:= 3, sleepDurationProvider:= Function(attempt) TimeSpan.FromSeconds(Math.Pow(2, attempt)), onRetry:= Sub(exception, timeSpan, retryCount, context)
Console.WriteLine($"Retry {retryCount} due to {exception.Message}")
End Sub)Dim retryPolicy = Policy.Handle(Of HttpRequestException)().WaitAndRetry(retryCount:= 3, sleepDurationProvider:= Function(attempt) TimeSpan.FromSeconds(Math.Pow(2, attempt)), onRetry:= Sub(exception, timeSpan, retryCount, context)
Console.WriteLine($"Retry {retryCount} due to {exception.Message}")
End Sub)
サーキットブレイカーを伴うリトライ
リトライとサーキットブレーカーの組み合わせは、サービスが継続的に失敗する場合に繰り返しリトライするのを防ぐことで回復力をさらに向上させることができます。 Pollyでは、リトライとサーキットブレーカーのポリシーを簡単に組み合わせることができます。
// Define a circuit breaker policy
var circuitBreakerPolicy = Policy
.Handle<HttpRequestException>()
.CircuitBreaker(
exceptionsAllowedBeforeBreaking: 3, // Number of exceptions before breaking
durationOfBreak: TimeSpan.FromSeconds(30), // Time circuit stays open
onBreak: (ex, breakDelay) =>
{
Console.WriteLine($"Circuit broken due to {ex.Message}. Retry after {breakDelay.TotalSeconds} seconds.");
},
onReset: () =>
{
Console.WriteLine("Circuit reset.");
});
// Define a retry policy
var retryPolicy = Policy
.Handle<HttpRequestException>()
.WaitAndRetry(
retryCount: 3, // Max retry attempts
sleepDurationProvider: attempt => TimeSpan.FromSeconds(2), // Fixed retry delay
onRetry: (exception, timeSpan, retryCount, context) =>
{
Console.WriteLine($"Retry {retryCount} due to {exception.Message}");
});
// Combine both policies into a single policy wrap
var policyWrap = Policy.Wrap(circuitBreakerPolicy, retryPolicy);// Define a circuit breaker policy
var circuitBreakerPolicy = Policy
.Handle<HttpRequestException>()
.CircuitBreaker(
exceptionsAllowedBeforeBreaking: 3, // Number of exceptions before breaking
durationOfBreak: TimeSpan.FromSeconds(30), // Time circuit stays open
onBreak: (ex, breakDelay) =>
{
Console.WriteLine($"Circuit broken due to {ex.Message}. Retry after {breakDelay.TotalSeconds} seconds.");
},
onReset: () =>
{
Console.WriteLine("Circuit reset.");
});
// Define a retry policy
var retryPolicy = Policy
.Handle<HttpRequestException>()
.WaitAndRetry(
retryCount: 3, // Max retry attempts
sleepDurationProvider: attempt => TimeSpan.FromSeconds(2), // Fixed retry delay
onRetry: (exception, timeSpan, retryCount, context) =>
{
Console.WriteLine($"Retry {retryCount} due to {exception.Message}");
});
// Combine both policies into a single policy wrap
var policyWrap = Policy.Wrap(circuitBreakerPolicy, retryPolicy);' Define a circuit breaker policy
Dim circuitBreakerPolicy = Policy.Handle(Of HttpRequestException)().CircuitBreaker(exceptionsAllowedBeforeBreaking:= 3, durationOfBreak:= TimeSpan.FromSeconds(30), onBreak:= Sub(ex, breakDelay)
Console.WriteLine($"Circuit broken due to {ex.Message}. Retry after {breakDelay.TotalSeconds} seconds.")
End Sub, onReset:= Sub()
Console.WriteLine("Circuit reset.")
End Sub)
' Define a retry policy
Dim retryPolicy = Policy.Handle(Of HttpRequestException)().WaitAndRetry(retryCount:= 3, sleepDurationProvider:= Function(attempt) TimeSpan.FromSeconds(2), onRetry:= Sub(exception, timeSpan, retryCount, context)
Console.WriteLine($"Retry {retryCount} due to {exception.Message}")
End Sub)
' Combine both policies into a single policy wrap
Dim policyWrap = Policy.Wrap(circuitBreakerPolicy, retryPolicy)' Define a circuit breaker policy
Dim circuitBreakerPolicy = Policy.Handle(Of HttpRequestException)().CircuitBreaker(exceptionsAllowedBeforeBreaking:= 3, durationOfBreak:= TimeSpan.FromSeconds(30), onBreak:= Sub(ex, breakDelay)
Console.WriteLine($"Circuit broken due to {ex.Message}. Retry after {breakDelay.TotalSeconds} seconds.")
End Sub, onReset:= Sub()
Console.WriteLine("Circuit reset.")
End Sub)
' Define a retry policy
Dim retryPolicy = Policy.Handle(Of HttpRequestException)().WaitAndRetry(retryCount:= 3, sleepDurationProvider:= Function(attempt) TimeSpan.FromSeconds(2), onRetry:= Sub(exception, timeSpan, retryCount, context)
Console.WriteLine($"Retry {retryCount} due to {exception.Message}")
End Sub)
' Combine both policies into a single policy wrap
Dim policyWrap = Policy.Wrap(circuitBreakerPolicy, retryPolicy)この例では:
CircuitBreaker()は、3 つの例外後にブレークし、30 秒間開いたままであるサーキットブレーカーポリシーを定義します。Policy.Wrap()は、サーキットブレーカーとリトライポリシーを単一のポリシーに結合します。

IronPDFの紹介
IronPDF C# PDF Library Overviewは、開発者が.NETアプリケーション内でPDFドキュメントを作成、編集、および操作できる強力なC#ライブラリです。 請求書、レポート、その他のタイプのPDFドキュメントを作成する必要がある場合、IronPDFはプロセスを簡単にする直感的なAPIを提供します。
IronPDFを使用すると、HTML、CSS、さらにはASP.NET WebページをPDFに簡単に変換でき、幅広い用途に対応する汎用ツールとなります。 また、テキストの追加、画像、インタラクティブ要素の追加、暗号化やデジタル署名によるPDFの保護などの高度な機能も提供しています。
IronPDFはHTMLをPDFに変換する機能に優れており、元のレイアウトやスタイルを正確に保ちます。 レポート、請求書、ドキュメントなどのWebベースのコンテンツからPDFを生成するのに最適です。 IronPDFは、HTMLファイル、URL、生のHTML文字列から高品質の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");
}
}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 ClassImports 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 ClassPolly RetryとIronPDF
IronPDFを使用する際には、外部ソースからデータを取得したり、PDFを生成する前に複雑な操作を行ったりする必要があるシナリオがあるかもしれません。
そのような場合、一時的な障害や一時的な問題によりPDF生成が失敗することがあります。 これらの一時的な障害をスムーズに処理するために、Polly RetryをIronPDFと組み合わせて使用できます。
IronPDFとPollyのインストール
始める前に、プロジェクトにIronPDFのNuGetパッケージをインストールしてください。
Polly RetryをIronPDFと一緒に使用する
IronPDFを使用してPDFを生成する際の一時的な障害を処理するために、Polly Retryを使用する例を見てみましょう。 次の例では、外部APIからデータを取得し、そのデータに基づいてPDFを生成する操作をシミュレートします。 当社では、Polly Retry を使用して、データ取得操作を失敗した場合に実行します。
using System;
using System.Net.Http;
using System.Threading.Tasks;
using IronPdf;
using Polly;
namespace IronPdfWithPollyRetry
{
public class Program
{
public static async Task Main(string[] args)
{
// Define a retry policy with async capability
var retryPolicy = Policy
.Handle<HttpRequestException>() // Specify exception type to handle
.WaitAndRetryAsync(
3, // Retry attempts
retryAttempt => TimeSpan.FromSeconds(2), // Calculated retry delay
(exception, timeSpan, retryCount, context) =>
{
Console.WriteLine("Retry " + retryCount + " due to " + exception.Message);
});
// Execute the retry policy asynchronously
var pdf = await retryPolicy.ExecuteAsync(async () =>
{
var data = await FetchDataFromExternalApiAsync(); // Fetch data from an external source
return GeneratePdfFromData(data); // Generate PDF using fetched data
});
pdf.SaveAs("GeneratedDocument.pdf");
}
// Simulate fetching data from an external API
static async Task<string> FetchDataFromExternalApiAsync()
{
await Task.Delay(100); // Simulate delay
throw new HttpRequestException("Failed to fetch data from external API");
}
// Generate PDF using IronPDF based on the fetched data
static PdfDocument GeneratePdfFromData(string data)
{
var htmlContent = "<html><body><h1>Data: " + data + "</h1></body></html>";
var renderer = new ChromePdfRenderer();
return renderer.RenderHtmlAsPdf(htmlContent);
}
}
}using System;
using System.Net.Http;
using System.Threading.Tasks;
using IronPdf;
using Polly;
namespace IronPdfWithPollyRetry
{
public class Program
{
public static async Task Main(string[] args)
{
// Define a retry policy with async capability
var retryPolicy = Policy
.Handle<HttpRequestException>() // Specify exception type to handle
.WaitAndRetryAsync(
3, // Retry attempts
retryAttempt => TimeSpan.FromSeconds(2), // Calculated retry delay
(exception, timeSpan, retryCount, context) =>
{
Console.WriteLine("Retry " + retryCount + " due to " + exception.Message);
});
// Execute the retry policy asynchronously
var pdf = await retryPolicy.ExecuteAsync(async () =>
{
var data = await FetchDataFromExternalApiAsync(); // Fetch data from an external source
return GeneratePdfFromData(data); // Generate PDF using fetched data
});
pdf.SaveAs("GeneratedDocument.pdf");
}
// Simulate fetching data from an external API
static async Task<string> FetchDataFromExternalApiAsync()
{
await Task.Delay(100); // Simulate delay
throw new HttpRequestException("Failed to fetch data from external API");
}
// Generate PDF using IronPDF based on the fetched data
static PdfDocument GeneratePdfFromData(string data)
{
var htmlContent = "<html><body><h1>Data: " + data + "</h1></body></html>";
var renderer = new ChromePdfRenderer();
return renderer.RenderHtmlAsPdf(htmlContent);
}
}
}Imports System
Imports System.Net.Http
Imports System.Threading.Tasks
Imports IronPdf
Imports Polly
Namespace IronPdfWithPollyRetry
Public Class Program
Public Shared Async Function Main(ByVal args() As String) As Task
' Define a retry policy with async capability
Dim retryPolicy = Policy.Handle(Of HttpRequestException)().WaitAndRetryAsync(3, Function(retryAttempt) TimeSpan.FromSeconds(2), Sub(exception, timeSpan, retryCount, context)
Console.WriteLine("Retry " & retryCount & " due to " & exception.Message)
End Sub)
' Execute the retry policy asynchronously
Dim pdf = Await retryPolicy.ExecuteAsync(Async Function()
Dim data = Await FetchDataFromExternalApiAsync() ' Fetch data from an external source
Return GeneratePdfFromData(data) ' Generate PDF using fetched data
End Function)
pdf.SaveAs("GeneratedDocument.pdf")
End Function
' Simulate fetching data from an external API
Private Shared Async Function FetchDataFromExternalApiAsync() As Task(Of String)
Await Task.Delay(100) ' Simulate delay
Throw New HttpRequestException("Failed to fetch data from external API")
End Function
' Generate PDF using IronPDF based on the fetched data
Private Shared Function GeneratePdfFromData(ByVal data As String) As PdfDocument
Dim htmlContent = "<html><body><h1>Data: " & data & "</h1></body></html>"
Dim renderer = New ChromePdfRenderer()
Return renderer.RenderHtmlAsPdf(htmlContent)
End Function
End Class
End NamespaceImports System
Imports System.Net.Http
Imports System.Threading.Tasks
Imports IronPdf
Imports Polly
Namespace IronPdfWithPollyRetry
Public Class Program
Public Shared Async Function Main(ByVal args() As String) As Task
' Define a retry policy with async capability
Dim retryPolicy = Policy.Handle(Of HttpRequestException)().WaitAndRetryAsync(3, Function(retryAttempt) TimeSpan.FromSeconds(2), Sub(exception, timeSpan, retryCount, context)
Console.WriteLine("Retry " & retryCount & " due to " & exception.Message)
End Sub)
' Execute the retry policy asynchronously
Dim pdf = Await retryPolicy.ExecuteAsync(Async Function()
Dim data = Await FetchDataFromExternalApiAsync() ' Fetch data from an external source
Return GeneratePdfFromData(data) ' Generate PDF using fetched data
End Function)
pdf.SaveAs("GeneratedDocument.pdf")
End Function
' Simulate fetching data from an external API
Private Shared Async Function FetchDataFromExternalApiAsync() As Task(Of String)
Await Task.Delay(100) ' Simulate delay
Throw New HttpRequestException("Failed to fetch data from external API")
End Function
' Generate PDF using IronPDF based on the fetched data
Private Shared Function GeneratePdfFromData(ByVal data As String) As PdfDocument
Dim htmlContent = "<html><body><h1>Data: " & data & "</h1></body></html>"
Dim renderer = New ChromePdfRenderer()
Return renderer.RenderHtmlAsPdf(htmlContent)
End Function
End Class
End NamespaceこのC#コードは、IronPDFを使用してPDFドキュメントを生成するリトライポリシーを実装するためのPollyライブラリの使用方法を示しています。 Main メソッドは、Polly の WaitAndRetryAsync メソッドを使用してリトライポリシーを初期化します。
このポリシーは、HttpRequestException を処理し、初回試行とリトライの間に2秒の遅延を持ち、最大3回操作をリトライすることを指定します。 リトライ失敗が発生した場合、リトライ試行番号と例外メッセージを示すメッセージがコンソールに印刷されます。
Main メソッドの内部で、リトライポリシーのロジックは retryPolicy.ExecuteAsync() を使用して非同期で実行されます。 この実行の中で、2 つの非同期操作 FetchDataFromExternalApiAsync() と GeneratePdfFromData(data) が連鎖されています。
もし FetchDataFromExternalApiAsync() が失敗(シミュレートされた例外を使用して意図的に設定されています)した場合、リトライポリシーは HttpRequestException をキャッチし、リトライ試行をログに記録して操作をリトライします。
FetchDataFromExternalApiAsync() メソッドは、外部 API からデータを取得することをシミュレートし、遅延を伴い、失敗したリクエストをシミュレートするために意図的に HttpRequestException をスローします。

結論
結論として、Pollyのリトライポリシーは一時的な障害を処理し、堅牢性を確保するのに非常に価値があります。 リトライ試行、遅延、および条件を設定する柔軟性により、開発者は特定の要件に応じた復元力の戦略をカスタマイズできます。
IronPDFのようなライブラリと独立して、または組み合わせて使用するかにかかわらず、Pollyは一時的な障害から回復し、ユーザーエクスペリエンスとソフトウェアの信頼性を向上させるアプリケーションの作成を促進します。
Pollyのリトライ機能を統合することにより、開発者は、一時的な問題に適応し回復することができるより回復力のあるシステムを構築し、最終的にアプリケーションの全体的な品質と信頼性を向上させることができます。
IronPDF は市場で最高の C# PDF ライブラリであり、IronPDF のトライアルライセンス も提供しており、価格は $999 米ドルからです。
IronPDFを使用したHTMLからPDFへの変換について学ぶには、次のIronPDF HTML to PDF Conversion Tutorialを参照してください。
ジェイコブ・メラーはIron Softwareの最高技術責任者(CTO)であり、C# PDFテクノロジーを開拓する先見的なエンジニアです。Iron Softwareのコアコードベースを支えるオリジナル開発者として、彼は創業以来、会社の製品アーキテクチャを形成し、CEOのCameron Rimingtonとともに、会社をNASA、Tesla、および世界的な政府機関にサービスを提供する50人以上の会社に変えました。1999年にロンドンで最初のソフトウェアビジネスを開業し、2005年に最初 for .NETコンポーネントを作成した後、Microsoftのエコシステム全体で複雑な問題を解決することを専門としました。