.NET 도움말 Polly Retry (How It Works For Developers) 커티스 차우 업데이트됨:7월 28, 2025 다운로드 IronPDF NuGet 다운로드 DLL 다운로드 윈도우 설치 프로그램 무료 체험 시작하기 LLM용 사본 LLM용 사본 LLM용 마크다운 형식으로 페이지를 복사하세요 ChatGPT에서 열기 ChatGPT에 이 페이지에 대해 문의하세요 제미니에서 열기 제미니에게 이 페이지에 대해 문의하세요 Grok에서 열기 Grok에게 이 페이지에 대해 문의하세요 혼란 속에서 열기 Perplexity에게 이 페이지에 대해 문의하세요 공유하다 페이스북에 공유하기 트위터에 공유하기 LinkedIn에 공유하기 URL 복사 이메일로 기사 보내기 Handling transient faults, timeouts, and exceptions gracefully is crucial in building robust and resilient applications. Polly is a popular .NET library that provides resilience and transient fault handling capabilities. Among its many features, "retry" is one of the most widely used policies. In this article, we'll delve into Polly's retry policy in C#, exploring its usage, and configuration options, and providing practical code examples. Also, we will use the IronPDF Library for PDF Generation with the Polly Retry attempt to generate a PDF of form request results. What is Polly Retry? Polly Retry is a policy provided by the Polly library that enables developers to automatically retry operations that might fail due to an error or transient faults. Transient faults are temporary errors that occur due to network glitches, service unavailability, or other transient issues. With Polly's retry policy, you can define rules for retrying operations, including the maximum number of retries, the delay between multiple retries, and conditions for retrying a failed request. This helps in building resilient applications that can recover from temporary failures without crashing or causing disruptions to end-users. Getting Started with Polly Retry Before diving into code examples, let's set up a basic understanding of how to install and configure Polly in a C# project. Installing Polly You can install Polly via the NuGet Package Manager Console using the following command: Install-Package Polly Or via .NET CLI: dotnet add package Polly Adding Polly using statements In your C# file, include the Polly namespace: using Polly; using Polly; $vbLabelText $csharpLabel Basic Retry Policy Example Let's start with a simple example where we retry an operation that simulates fetching data from a remote service. We'll set up a retry policy with a maximum of 3 retries and a fixed timeout delay of 2 seconds between retries. 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"); } } } $vbLabelText $csharpLabel In this example: Handle<HttpRequestException>() specifies that we want to handle HttpRequestException and retry the operation if it occurs. WaitAndRetry() configures the retry policy with 3 retries and a fixed delay of 2 seconds between retries (specified maximum duration). onRetry delegate logs a message when a retry occurs. Advanced Retry Policy Configuration Exponential Backoff Exponential backoff is a popular retry strategy where the delay between requests and retries increases exponentially. Polly provides a convenient way to implement exponential backoff using 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}"); }); $vbLabelText $csharpLabel Retry with Circuit Breaker Combining retry with a circuit breaker can further enhance resilience by preventing repeated retries when a service is consistently failing. Polly allows you to combine retry and circuit breaker policies easily. // 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); $vbLabelText $csharpLabel In this example: CircuitBreaker() defines a circuit breaker policy that breaks after 3 exceptions and stays open for 30 seconds. Policy.Wrap() combines the circuit breaker and retry policies into a single policy. Introduction to IronPDF IronPDF C# PDF Library Overview is a powerful C# library that allows developers to create, edit, and manipulate PDF documents within their .NET applications. Whether you need to create invoices, reports, or any other type of PDF document, IronPDF provides an intuitive API that simplifies the process. With IronPDF, you can easily convert HTML, CSS, and even ASP.NET web pages to PDF, making it a versatile tool for a wide range of applications. Additionally, it offers advanced features like adding text, images, and interactive elements to PDFs, as well as securing them with encryption and digital signatures. IronPDF excels at HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for generating PDFs from web-based content such as reports, invoices, and documentation. IronPDF supports conversion from HTML files, URLs, and raw HTML strings into high-quality PDF files. 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"); } } $vbLabelText $csharpLabel Polly Retry with IronPDF When working with IronPDF, there might be scenarios where you need to fetch data from external sources or perform complex operations before generating a PDF. In such cases, you might encounter transient faults or temporary issues that could lead to PDF generation failures. To handle these transient faults gracefully, you can use Polly Retry in conjunction with IronPDF. Installing IronPDF and Polly Before getting started, make sure to install the IronPDF NuGet package in your project. Install-Package IronPdf Using Polly Retry with IronPDF Let's look at an example where we use Polly Retry to handle transient faults when generating a PDF using IronPDF. In the following example, we'll simulate fetching data from an external API and then generating a PDF based on that data. We'll use Polly Retry to execute the data fetching operation in case of failures. 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); } } } $vbLabelText $csharpLabel This C# code demonstrates how to use the Polly library for implementing retry policies with IronPDF to generate a PDF document. The Main method initializes a retry policy using Polly's WaitAndRetryAsync method. This policy specifies that it should handle HttpRequestException and retry the operation up to 3 times with a delay of 2 seconds between the initial attempt and retries. If a retry failure occurs, a message is printed to the console indicating the retry attempt number and the exception message. Inside the Main method, the retry policy logic is executed asynchronously using retryPolicy.ExecuteAsync(). Within this execution, two asynchronous operations are chained together: FetchDataFromExternalApiAsync() and GeneratePdfFromData(data). If FetchDataFromExternalApiAsync() fails (as it's intentionally set up to do with a simulated exception), the retry policy will catch the HttpRequestException, log the retry attempt, and retry the operation. The FetchDataFromExternalApiAsync() method simulates fetching data from an external API with a delay and intentionally throws an HttpRequestException to simulate failed requests. Conclusion In conclusion, Polly's retry policy proves invaluable for handling transient faults and ensuring robustness in C# applications. Its flexibility in configuring retry attempts, delays, and conditions allows developers to tailor resilience strategies to specific requirements. Whether used independently or in conjunction with libraries like IronPDF, Polly facilitates the creation of applications that gracefully recover from temporary failures, enhancing the user experience and reliability of the software. By integrating Polly's retry capabilities, developers can build more resilient systems that can adapt and recover from transient issues, ultimately improving the overall quality and dependability of their applications. IronPDF is the best C# PDF library on the market, it also offers a trial license for IronPDF prices start from $799 USD. To learn about HTML to PDF conversion using IronPDF visit the following IronPDF HTML to PDF Conversion Tutorial. 자주 묻는 질문 C#에서 폴리 재시도란 무엇인가요? Polly 재시도는 개발자가 네트워크 결함이나 서비스 사용 불가와 같은 일시적인 문제로 인해 실패한 작업을 자동으로 재시도할 수 있는 C#의 Polly 라이브러리 기능입니다. 이를 통해 일시적인 오류를 원활하게 처리하여 탄력적인 애플리케이션을 구축하는 데 도움이 됩니다. Polly를 사용하여 기본 재시도 정책을 구현하려면 어떻게 해야 하나요? HttpRequestException과 같은 예외를 처리하고 각 시도 사이에 2초의 고정 지연을 두고 최대 3회 재시도하도록 설정하여 Polly에서 기본 재시도 정책을 구현할 수 있습니다. Polly에서 지수 백오프의 의미는 무엇인가요? Polly의 지수 백오프는 재시도 사이의 지연을 기하급수적으로 늘리는 데 사용되며, 이는 장애 발생 시 서비스 부하를 줄이는 데 도움이 됩니다. 이는 지수 증가에 따라 지연을 계산하는 Polly의 WaitAndRetry 메서드를 사용하여 구현할 수 있습니다. C# 프로젝트에 Polly를 설치하려면 어떻게 해야 하나요? C# 프로젝트에 Polly를 설치하려면 NuGet 패키지 관리자 콘솔에서 Install-Package Polly 명령을 사용하거나 .NET CLI에서 dotnet add package Polly로 설치할 수 있습니다. Polly의 재시도 정책을 다른 회복탄력성 전략과 결합할 수 있나요? 예, Polly를 사용하면 재시도 정책을 회로 차단기와 같은 다른 복원력 전략과 결합하여 Policy.Wrap 방법을 사용하여 애플리케이션 복원력을 향상시키고 서비스가 지속적으로 실패할 때 반복되는 재시도를 방지할 수 있습니다. C#에서 HTML을 PDF로 변환하려면 어떻게 해야 하나요? IronPDF의 RenderHtmlAsPdf와 같은 메서드를 사용하여 HTML 문자열을 PDF로 변환할 수 있습니다. IronPDF는 CSS를 포함한 HTML 파일과 웹 페이지를 PDF 형식으로 변환하는 기능도 지원합니다. Polly의 재시도 정책이 C# 애플리케이션에 중요한 이유는 무엇인가요? Polly의 재시도 정책은 C# 애플리케이션의 일시적인 오류를 처리하고 견고성을 보장하며 시스템이 충돌 없이 일시적인 오류로부터 복구할 수 있도록 하여 사용자 환경을 개선하는 데 매우 중요합니다. PDF 생성 프로세스에서 재시도 전략을 어떻게 구현할 수 있나요? PDF를 생성할 때 일시적인 오류를 처리하기 위해 Polly를 사용하여 재시도 전략을 구현할 수 있습니다. Polly의 재시도 기능을 IronPDF와 통합하면 일시적인 네트워크 또는 서비스 문제가 발생하는 경우 PDF 작업을 여러 번 시도할 수 있습니다. IronPDF와 같은 C# PDF 라이브러리는 어떻게 설치하나요? IronPDF는 NuGet 패키지 관리자를 통해 Install-Package IronPdf 명령으로 설치할 수 있으며, C# 애플리케이션 내에서 PDF 문서를 생성, 편집 및 조작할 수 있습니다. PDF 생성에 IronPDF를 사용하면 어떤 이점이 있나요? IronPDF는 .NET 애플리케이션에서 PDF 문서를 만들고 조작할 수 있는 강력한 기능을 제공합니다. HTML, CSS, 웹 페이지를 PDF로 변환하고, 텍스트와 이미지를 추가하고, 암호화를 통해 문서를 보호하는 기능을 지원합니다. 커티스 차우 지금 바로 엔지니어링 팀과 채팅하세요 기술 문서 작성자 커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다. 커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다. 관련 기사 업데이트됨 12월 11, 2025 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 더 읽어보기 업데이트됨 12월 20, 2025 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 더 읽어보기 업데이트됨 12월 20, 2025 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기 C# iList (How It Works For Developers)WebClient C# (How It Works For Deve...
업데이트됨 12월 11, 2025 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 더 읽어보기
업데이트됨 12월 20, 2025 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 더 읽어보기
업데이트됨 12월 20, 2025 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기