.NET 도움말 .NET Core Polly (How it Works for Developers) 커티스 차우 업데이트됨:7월 28, 2025 다운로드 IronPDF NuGet 다운로드 DLL 다운로드 윈도우 설치 프로그램 무료 체험 시작하기 LLM용 사본 LLM용 사본 LLM용 마크다운 형식으로 페이지를 복사하세요 ChatGPT에서 열기 ChatGPT에 이 페이지에 대해 문의하세요 제미니에서 열기 제미니에게 이 페이지에 대해 문의하세요 Grok에서 열기 Grok에게 이 페이지에 대해 문의하세요 혼란 속에서 열기 Perplexity에게 이 페이지에 대해 문의하세요 공유하다 페이스북에 공유하기 트위터에 공유하기 LinkedIn에 공유하기 URL 복사 이메일로 기사 보내기 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}"); }); $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)); $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 $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 $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; }); $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); $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"); } } $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; $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)); $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"); $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}"); } } $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. 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. 자주 묻는 질문 Polly란 무엇이며 어떻게 .NET Core 복원력을 향상하나요? Polly는 복원력 및 일시적인 오류 처리를 위해 설계된 .NET 라이브러리로, 특히 ASP.NET Core 애플리케이션을 위해 설계되었습니다. 재시도, 회로 차단기, 타임아웃, 벌크헤드 격리, 폴백 등의 전략을 제공하여 복원력을 향상시켜 견고하고 내결함성 있는 시스템을 보장합니다. Polly를 사용하여 .NET Core에서 재시도 정책을 구현하려면 어떻게 해야 하나요? .NET Core에서는 Polly를 사용하여 실패한 요청을 자동으로 재시도하도록 구성하여 재시도 정책을 구현할 수 있습니다. 재시도 횟수와 시도 간 시간 간격을 설정하여 일시적인 오류를 효과적으로 관리할 수 있습니다. 회로 차단기 정책은 .NET 애플리케이션에서 연쇄적인 장애를 어떻게 방지하나요? Polly의 회로 차단기 정책은 장애를 모니터링하고 장애 임계값에 도달하면 회로를 열어 요청을 차단함으로써 연쇄적인 장애를 방지합니다. 이렇게 하면 회로가 재설정될 때까지 추가 요청이 중지되어 시스템이 새로운 요청을 수락하기 전에 복구할 수 있습니다. 벌크헤드 격리는 리소스 고갈을 관리하는 데 어떤 역할을 하나요? Polly의 벌크헤드 격리는 서비스에 대한 동시 요청 수를 제한하여 실행 슬롯을 제어함으로써 리소스 고갈을 방지합니다. 이 정책은 장애를 억제하고 .NET Core 애플리케이션 내에서 효율적인 리소스 관리를 보장하는 데 도움이 됩니다. Polly의 시간 초과 정책으로 내 애플리케이션의 응답성을 어떻게 개선할 수 있나요? Polly의 시간 초과 정책은 작업의 최대 실행 시간을 적용하여 서비스가 즉각적으로 응답하지 않는 시나리오를 관리하는 데 도움이 됩니다. 개발자는 낙관적 또는 비관적 시간 제한을 설정하여 애플리케이션의 응답성을 유지할 수 있습니다. Polly를 사용하여 URL을 PDF로 변환할 때 신뢰성을 높일 수 있나요? 예, Polly는 재시도 및 서킷 브레이커 정책을 PDF 생성 도구와 통합하여 URL을 PDF로 변환하는 안정성을 향상시킬 수 있습니다. 이를 통해 변환 프로세스가 일시적인 오류에 탄력적으로 대응하여 안정성을 유지할 수 있습니다. Polly의 폴백 정책은 어떻게 서비스의 점진적인 저하를 보장하나요? Polly의 폴백 정책은 서비스 장애 시 대체 응답 또는 동작을 제공합니다. 이를 통해 장애로 인해 전체 애플리케이션이 중단되지 않도록 하여 점진적인 성능 저하를 방지하고 계속 운영할 수 있습니다. .NET 애플리케이션에서 여러 Polly 정책을 어떻게 결합하나요? .NET 애플리케이션에서는 정책 랩을 사용하여 여러 Polly 정책을 결합할 수 있습니다. 이를 통해 개발자는 다양한 복원력 전략을 함께 실행할 수 있으므로 보다 포괄적이고 유연한 장애 처리 접근 방식을 구현할 수 있습니다. Polly와 IronPDF를 통합하면 PDF 생성 시 일시적인 결함을 어떻게 처리하나요? Polly와 IronPDF를 통합하면 개발자는 재시도 및 회로 차단기와 같은 정책을 통해 PDF 생성 중 일시적인 결함을 처리할 수 있습니다. 이러한 통합으로 간헐적인 서비스 중단에도 불구하고 안정적이고 신뢰할 수 있는 PDF 생성이 보장됩니다. Polly를 .NET Core와 함께 사용할 때 일반적인 문제 해결 전략은 무엇인가요? 일반적인 문제 해결 전략에는 재시도 간격 및 회로 차단기 임계값과 같은 정책 구성을 확인하고 다양한 시나리오로 정책을 테스트하여 결함의 적절한 처리 및 시스템 복원력을 보장하는 것이 포함됩니다. 커티스 차우 지금 바로 엔지니어링 팀과 채팅하세요 기술 문서 작성자 커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, 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# Split String (How it Works for Developers)Blazor vs MVC (How It Works For Dev...
업데이트됨 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 더 읽어보기