.NET 도움말 C# Cancellationtoken (How It Works For Developers) 커티스 차우 업데이트됨:6월 22, 2025 다운로드 IronPDF NuGet 다운로드 DLL 다운로드 윈도우 설치 프로그램 무료 체험 시작하기 LLM용 사본 LLM용 사본 LLM용 마크다운 형식으로 페이지를 복사하세요 ChatGPT에서 열기 ChatGPT에 이 페이지에 대해 문의하세요 제미니에서 열기 제미니에게 이 페이지에 대해 문의하세요 Grok에서 열기 Grok에게 이 페이지에 대해 문의하세요 혼란 속에서 열기 Perplexity에게 이 페이지에 대해 문의하세요 공유하다 페이스북에 공유하기 트위터에 공유하기 LinkedIn에 공유하기 URL 복사 이메일로 기사 보내기 In modern software development, managing long-running tasks efficiently is critical, especially in applications where generating large or complex PDF files is common. C# developers often rely on IronPDF for seamless PDF creation, but handling potentially lengthy PDF generation tasks requires a way to manage user interruptions or cancellations. This is where the CancellationToken in C# comes into play. By integrating it with IronPDF, you can ensure your PDF generation tasks are both responsive and efficient. In this article, we'll explore the importance of CancellationToken, why it pairs well with IronPDF, and how you can implement it to cancel tasks gracefully. What is a CancellationToken in C#? The CancellationToken is a fundamental part of asynchronous programming in C#. It allows you to signal that a task should be cancelled, giving developers greater control over long-running operations. This can be especially helpful when carrying out tasks such as producing reports or invoices, where you might want to continuously generate dynamic reports from data until you've hit your goal amount, by which point you can use C# cancellation tokens to indicate that the operation should be cancelled, which gracefully ends the program. How does it work? In essence, a CancellationToken is passed to a task or method, which periodically checks if cancellation has been requested. If so, the task can gracefully terminate, freeing up resources and improving the responsiveness of your application. This is particularly useful in cases like PDF generation, where complex documents might take time to create. By using CancellationTokens, you avoid the potential downsides of tasks that run unnecessarily long, such as wasted system resources and a poor user experience. Internal Cancellation Tokens In C#, an internal cancellation token refers to a cancellation token that is created and managed within a specific class or method, rather than being passed in from an external source. This allows for finer control over task cancellation within the scope of a single component, enabling it to monitor and respond to cancellation requests that originate internally. Using an internal cancellation token is particularly useful in scenarios where you want to encapsulate cancellation logic without exposing it to the consumers of your class, thereby maintaining a clean interface. This approach can enhance code modularity and make it easier to manage complex asynchronous workflows while still leveraging the flexibility provided by the broader CancellationToken framework. Why Use a Cancellation Token with IronPDF? When generating PDFs, especially in web applications or complex reporting systems, you might encounter situations where a user initiates a task, such as creating a large PDF file, but then navigates away or no longer requires the result. In these cases, you want the option to cancel the PDF generation process to avoid unnecessary load on the server or UI. Here’s why using CancellationToken with IronPDF is crucial: 1. Prevent Unnecessary Load If a user no longer needs the PDF they requested, there's no reason for the process to continue. By utilizing CancellationToken, you can halt the PDF generation task, preventing excess load on your servers and improving overall application performance. 2. Enhance User Experience In desktop applications, PDF generation might occur on the UI thread, which could lock up the user interface if the task is long-running. By incorporating CancellationToken, users can cancel the task and keep the application responsive. 3. Improve Scalability In web applications where numerous users generate PDFs concurrently, scalability is key. CancellationToken allows you to safely cancel unnecessary tasks, freeing up resources to handle other requests efficiently. How to Implement CancellationToken with IronPDF Now that we understand why CancellationToken is useful, let's walk through how to implement it with IronPDF. Step 1: Setting Up IronPDF in Your Project To start using IronPDF, you will first need to install it. If it's already installed, then you can skip to the next section; otherwise, the following steps cover how to install the IronPDF library. Via the NuGet Package Manager Console To install IronPDF using the NuGet Package Manager Console, open Visual Studio and navigate to the Package Manager Console. Then run the following command: Install-Package IronPdf Via the NuGet Package Manager for Solution Opening Visual Studio, go to "Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution" and search for IronPDF. From here, all you need to do is select your project and click "Install", and IronPDF will be added to your project. Once you have installed IronPDF, all you need to add to start using IronPDF is the correct using statement at the top of your code: using IronPdf; using IronPdf; $vbLabelText $csharpLabel Step 2: Using Cancellation Tokens in an Asynchronous PDF Generation Method Let’s dive into the actual implementation. In this example, we’ll generate a simple PDF from HTML using IronPDF, but with a CancellationToken that allows the task to be canceled if necessary. using IronPdf; using System; using System.Threading; using System.Threading.Tasks; public class PdfGenerator { public async Task GeneratePdfWithCancellation(CancellationToken token) { var Renderer = new ChromePdfRenderer(); try { // Check for cancellation before starting token.ThrowIfCancellationRequested(); // Simulating a long task that can be checked for cancellation periodically for (int i = 0; i < 10; i++) { // Simulating a piece of work (this could be part of a larger HTML rendering) await Task.Delay(500); // Simulate chunk processing // Periodically check for cancellation in long-running operations if (token.IsCancellationRequested) { Console.WriteLine("Cancellation requested. Throwing exception."); token.ThrowIfCancellationRequested(); // This will trigger an OperationCanceledException } } // Simulate PDF creation after the long process var pdf = await Renderer.RenderHtmlAsPdfAsync("<h1>Hello, PDF!</h1>"); // Save the PDF after ensuring no cancellation occurred pdf.SaveAs("output.pdf"); Console.WriteLine("PDF generated successfully."); } catch (OperationCanceledException) { // Handle task cancellation Console.WriteLine("PDF generation was canceled."); } catch (Exception ex) { // Handle other exceptions Console.WriteLine($"An error occurred: {ex.Message}"); } } } public class Program { public static async Task Main(string[] args) { // Create a CancellationTokenSource var cancellationTokenSource = new CancellationTokenSource(); // Create our cancellation token var token = cancellationTokenSource.Token; // Start the PDF generation task var pdfGenerator = new PdfGenerator(); Task pdfTask = pdfGenerator.GeneratePdfWithCancellation(token); // Simulate a cancellation scenario Console.WriteLine("Press any key to cancel PDF generation..."); Console.ReadKey(); // Cancel the task by calling Cancel() on the CancellationTokenSource cancellationTokenSource.Cancel(); try { // Await the task to handle any exceptions, such as cancellation await pdfTask; } catch (OperationCanceledException) { // Confirm the cancellation Console.WriteLine("The PDF generation was canceled."); } finally { cancellationTokenSource.Dispose(); } Console.WriteLine("Program finished."); } } using IronPdf; using System; using System.Threading; using System.Threading.Tasks; public class PdfGenerator { public async Task GeneratePdfWithCancellation(CancellationToken token) { var Renderer = new ChromePdfRenderer(); try { // Check for cancellation before starting token.ThrowIfCancellationRequested(); // Simulating a long task that can be checked for cancellation periodically for (int i = 0; i < 10; i++) { // Simulating a piece of work (this could be part of a larger HTML rendering) await Task.Delay(500); // Simulate chunk processing // Periodically check for cancellation in long-running operations if (token.IsCancellationRequested) { Console.WriteLine("Cancellation requested. Throwing exception."); token.ThrowIfCancellationRequested(); // This will trigger an OperationCanceledException } } // Simulate PDF creation after the long process var pdf = await Renderer.RenderHtmlAsPdfAsync("<h1>Hello, PDF!</h1>"); // Save the PDF after ensuring no cancellation occurred pdf.SaveAs("output.pdf"); Console.WriteLine("PDF generated successfully."); } catch (OperationCanceledException) { // Handle task cancellation Console.WriteLine("PDF generation was canceled."); } catch (Exception ex) { // Handle other exceptions Console.WriteLine($"An error occurred: {ex.Message}"); } } } public class Program { public static async Task Main(string[] args) { // Create a CancellationTokenSource var cancellationTokenSource = new CancellationTokenSource(); // Create our cancellation token var token = cancellationTokenSource.Token; // Start the PDF generation task var pdfGenerator = new PdfGenerator(); Task pdfTask = pdfGenerator.GeneratePdfWithCancellation(token); // Simulate a cancellation scenario Console.WriteLine("Press any key to cancel PDF generation..."); Console.ReadKey(); // Cancel the task by calling Cancel() on the CancellationTokenSource cancellationTokenSource.Cancel(); try { // Await the task to handle any exceptions, such as cancellation await pdfTask; } catch (OperationCanceledException) { // Confirm the cancellation Console.WriteLine("The PDF generation was canceled."); } finally { cancellationTokenSource.Dispose(); } Console.WriteLine("Program finished."); } } $vbLabelText $csharpLabel Console Output PDF Output In this example, we demonstrate how to use a CancellationToken in a C# program to cancel a long-running PDF generation task with IronPDF. The code is structured in two parts: the PDF generation process (PdfGenerator class) and the main program logic (Program class). Class PdfGenerator: This class contains a method that simulates generating a PDF file while supporting cancellation via a CancellationToken. We create our cancellation token source in the main method using CancellationTokenSource(), and then create our token object by passing the CancellationTokenSource's Token property to it. ChromePdfRenderer is used from the IronPDF library to render HTML content into a PDF document. The GeneratePdfWithCancellation method is asynchronous (async) and returns a Task. This method accepts a CancellationToken (token) to handle task cancellation through the cancellation request. The CancellationToken allows us to safely cancel long-running operations. However, cancellation is cooperative, meaning the task itself must periodically check the token status. In this code, we simulate a long task with periodic cancellation checks. The key point is that we manually check for cancellation (token.IsCancellationRequested) during the PDF generation process, ready to run the cancel method if the token is passed to it. If the user presses a key to signal cancellation of the program, the task stops gracefully and throws an OperationCanceledException, preventing the completion of the PDF generation in an appropriate and timely manner. The resulting PDF is saved as "output.pdf" if no cancellation occurred to prevent the program from running the complete task process. Real-World Use Cases of IronPDF with CancellationToken There are several practical situations where using one or multiple cancellation tokens with IronPDF can enhance your application’s performance and user experience. Here are a few examples: 1. Web Applications In a web application, users often initiate actions like generating reports in PDF format. However, if the user navigates away from the page or closes the browser, the system can detect this and use CancellationToken to stop the PDF generation process. HttpContext.Response.RegisterForDispose(CancellationTokenSource); HttpContext.Response.RegisterForDispose(CancellationTokenSource); $vbLabelText $csharpLabel This simple implementation allows web servers to scale more effectively by not dedicating resources to tasks that are no longer needed. 2. Long-Running Reports In reporting applications, users might request large datasets to be exported as PDFs. If the user changes their mind or makes an incorrect query, CancellationToken allows you to cancel the task mid-way, preventing resource wastage. 3. Background Services In background services or microservices, tasks that take a significant amount of time, like generating large PDF batches, can be managed more efficiently using CancellationToken. When the service is about to shut down or be scaled down, tasks in progress can be canceled cleanly, ensuring no data is lost or corrupted. Conclusion Now that we've come to the end of today's discussion on using cancellation tokens with IronPDF, you'll be able to implement them into your PDF projects like a pro! Using C# CancellationToken with IronPDF empowers you to build more efficient, responsive applications that handle PDF generation tasks gracefully. This approach enables a cooperative cancellation model, allowing tasks to check for cancellation requests at safe points during execution, rather than being abruptly terminated. Whether you're managing long-running reports, on-demand PDF generation in web applications, or background services, incorporating a CancellationToken, or multiple tokens simultaneously, ensures that unnecessary tasks can be canceled, preventing wasted resources and enhancing user experience. With just a few lines of code, you can improve your app’s scalability and responsiveness while giving users more control over their actions. If you haven’t yet explored IronPDF, now is the perfect time to try the free trial and discover how its powerful PDF generation capabilities can transform your C# projects. 자주 묻는 질문 취소 토큰을 사용하여 C#에서 장기 실행 작업을 관리하려면 어떻게 해야 하나요? 취소 토큰을 작업에 전달하고 취소 요청이 있는지 주기적으로 확인하여 장기 실행 작업에 취소 토큰을 통합할 수 있습니다. 이렇게 하면 작업을 정상적으로 종료하여 리소스를 확보하고 애플리케이션 응답성을 유지할 수 있습니다. PDF 생성에서 취소 토큰이 중요한 이유는 무엇인가요? PDF 생성에서 취소 토큰은 사용자가 페이지에서 다른 페이지로 이동하는 등 불필요하게 된 작업을 취소할 수 있도록 하여 리소스를 효율적으로 관리할 수 있도록 도와줍니다. 이를 통해 과도한 서버 부하를 방지하고 사용자 경험을 향상시킬 수 있습니다. C# PDF 생성 작업에서 취소 토큰을 구현하려면 어떻게 해야 하나요? C# PDF 생성 작업에서 취소 토큰을 구현하려면 메서드에 토큰을 전달하고 실행 중에 일정한 간격으로 취소 요청을 확인합니다. 취소가 감지되면 작업을 정상적으로 종료할 수 있습니다. PDF 생성에서 취소 토큰과 함께 비동기 메서드를 사용하는 목적은 무엇인가요? PDF 생성에 취소 토큰과 함께 비동기 메서드를 사용하면 작업을 비동기적으로 실행하여 애플리케이션 응답성을 개선하고 더 이상 필요하지 않은 경우 작업을 취소할 수 있습니다. 취소 토큰은 웹 애플리케이션에서 사용자 경험을 어떻게 개선하나요? 웹 애플리케이션은 취소 토큰을 활용하여 사용자가 다른 곳으로 이동할 때 PDF 생성과 같은 작업을 취소하여 불필요한 처리를 방지하고 애플리케이션의 응답성을 유지하여 사용자 경험을 향상시킬 수 있습니다. 비동기 PDF 생성에서 ChromePdfRenderer의 역할은 무엇인가요? ironPDF의 ChromePdfRenderer는 HTML 콘텐츠를 PDF 문서로 변환하는 데 사용됩니다. 비동기 작업을 지원하므로 취소 토큰을 사용하여 작업 수명 주기 및 응답성을 효과적으로 관리할 수 있습니다. PDF 생성 중에 취소 요청을 하면 어떻게 되나요? PDF 생성 중에 취소 요청이 있는 경우 작업은 취소 토큰 상태를 확인합니다. 취소가 감지되면 작업은 리소스를 절약하기 위해 프로세스를 중지하고 OperationCanceledException을 던집니다. 취소 토큰은 애플리케이션의 확장성을 어떻게 향상시키나요? 취소 토큰은 PDF 생성 시와 같이 애플리케이션이 불필요한 작업을 취소할 수 있도록 하여 확장성을 향상시켜 리소스 소비를 줄이고 애플리케이션의 전반적인 성능을 개선합니다. 백그라운드 서비스에서 취소 토큰을 사용하면 어떤 이점이 있나요? 백그라운드 서비스에서 취소 토큰을 사용하면 서비스 종료 중 또는 작업 확장 시 작업을 깔끔하게 취소할 수 있어 일괄 PDF 처리와 같은 장기 실행 작업을 관리할 수 있습니다. 취소 토큰과 IronPDF의 통합으로 애플리케이션 효율성이 어떻게 향상되나요? 취소 토큰을 IronPDF와 통합하면 불필요한 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# Select Case (How It Works For Developers)math.max C# (How It Works For Devel...
업데이트됨 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 더 읽어보기