Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
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.
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.
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.
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.
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:
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.
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.
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.
Now that we understand why CancellationToken is useful, let's walk through how to implement it with IronPDF.
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
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;
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();
// Creating our one 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();
// Creating our one 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.");
}
}
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).
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:
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);
This simple implementation allows web servers to scale more effectively by not dedicating resources to tasks that are no longer needed.
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.
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.
Now we've come to the end of todays discussion on using cancellationtokens 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 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.