.NET HELP

C# Cancellationtoken (How It Works For Developers)

Published December 15, 2024
Share:

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
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
VB   C#

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.

Broken image Add from Pixabay, select from your files or drag and drop an image here.

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;
Imports IronPdf
VB   C#

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();
        // 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.");
    }
}
Imports IronPdf
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Public Class PdfGenerator
	Public Async Function GeneratePdfWithCancellation(ByVal token As CancellationToken) As Task
		Dim Renderer = New ChromePdfRenderer()
		Try
			' Check for cancellation before starting
			token.ThrowIfCancellationRequested()
			' Simulating a long task that can be checked for cancellation periodically
			For i As Integer = 0 To 9
				' 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 Then
					Console.WriteLine("Cancellation requested. Throwing exception.")
					token.ThrowIfCancellationRequested() ' This will trigger an OperationCanceledException
				End If
			Next i
			' Simulate PDF creation after the long process
			Dim 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 e1 As OperationCanceledException
			' Handle task cancellation
			Console.WriteLine("PDF generation was canceled.")
		Catch ex As Exception
			' Handle other exceptions
			Console.WriteLine($"An error occurred: {ex.Message}")
		End Try
	End Function
End Class
Public Class Program
	Public Shared Async Function Main(ByVal args() As String) As Task
		' Create a CancellationTokenSource
		Dim cancellationTokenSource As New CancellationTokenSource()
		' Creating our one cancellation token
		Dim token = cancellationTokenSource.Token
		' Start the PDF generation task
		Dim pdfGenerator As New PdfGenerator()
		Dim pdfTask As Task = 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 e1 As OperationCanceledException
			' Confirm the cancellation
			Console.WriteLine("The PDF generation was canceled.")
		Finally
			cancellationTokenSource.Dispose()
		End Try
		Console.WriteLine("Program finished.")
	End Function
End Class
VB   C#

Console Output

C# Cancellationtoken (How It Works For Developers): Figure 2 - Console Output

PDF Output

C# Cancellationtoken (How It Works For Developers): Figure 3 - 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 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);
HttpContext.Response.RegisterForDispose(CancellationTokenSource)
VB   C#

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 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.

< PREVIOUS
C# Select Case (How It Works For Developers)
NEXT >
math.max C# (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,938,203 View Licenses >