Zum Fußzeileninhalt springen
.NET HILFE

C# CancellationToken (Wie es für Entwickler funktioniert)

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;
Imports 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.");
    }
}
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()

		' Create our 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
$vbLabelText   $csharpLabel

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

Häufig gestellte Fragen

Wie kann ich ein CancellationToken verwenden, um lang andauernde Aufgaben in C# zu verwalten?

Sie können ein CancellationToken in Ihre lang andauernden Aufgaben integrieren, indem Sie es an die Aufgabe übergeben und regelmäßig prüfen, ob eine Stornierung angefordert wurde. Dies ermöglicht die ordnungsgemäße Beendigung von Aufgaben, die Ressourcen freigibt und die Anwendungsreaktionsfähigkeit aufrechterhält.

Warum ist ein CancellationToken in der PDF-Erstellung wichtig?

In der PDF-Erstellung hilft ein CancellationToken, Ressourcen effizient zu verwalten, indem es ermöglicht, Aufgaben zu stornieren, wenn sie nicht mehr erforderlich sind, beispielsweise wenn ein Benutzer die Seite wechselt. Dies verhindert übermäßige Serverbelastung und verbessert die Benutzererfahrung.

Wie implementiere ich ein CancellationToken in einer C# PDF-Erstellungsaufgabe?

Um ein CancellationToken in einer C# PDF-Erstellungsaufgabe zu implementieren, übergeben Sie das Token an Ihre Methode und prüfen regelmäßig auf Stornierungsanfragen während der Ausführung. Wenn eine Stornierung erkannt wird, können Sie die Aufgabe ordnungsgemäß beenden.

Was ist der Zweck der Verwendung von asynchronen Methoden mit CancellationToken in der PDF-Erstellung?

Die Verwendung von asynchronen Methoden mit einem CancellationToken in der PDF-Erstellung ermöglicht es Aufgaben, asynchron zu laufen, wodurch die Reaktionsfähigkeit der Anwendung verbessert wird und es möglich wird, Aufgaben zu stornieren, wenn sie nicht mehr benötigt werden.

Wie verbessert ein CancellationToken die Benutzererfahrung in Webanwendungen?

Durch die Nutzung eines CancellationToken können Webanwendungen Aufgaben wie die PDF-Erstellung stornieren, wenn ein Benutzer weg navigiert, unnötige Verarbeitung vermeiden und die Anwendungsreaktionsfähigkeit aufrechterhalten, was die Benutzererfahrung verbessert.

Welche Rolle spielt ChromePdfRenderer in der asynchronen PDF-Erstellung?

ChromePdfRenderer von IronPDF wird verwendet, um HTML-Inhalt in ein PDF-Dokument zu konvertieren. Es unterstützt asynchrone Operationen, sodass Sie ein CancellationToken verwenden können, um den Lebenszyklus und die Reaktionsfähigkeit der Aufgabe effektiv zu verwalten.

Was kann passieren, wenn während der PDF-Erstellung eine Stornierungsanforderung gestellt wird?

Wenn während der PDF-Erstellung eine Stornierungsanforderung gestellt wird, überprüft die Aufgabe den Status des CancellationToken. Bei Erkennung einer Stornierung wird eine OperationCanceledException ausgelöst, wodurch der Prozess gestoppt wird, um Ressourcen zu sparen.

Wie verbessert CancellationToken die Skalierbarkeit von Anwendungen?

CancellationToken verbessert die Skalierbarkeit, indem Anwendungen ermöglicht wird, unnötige Aufgaben zu stornieren, wie beispielsweise bei der PDF-Erstellung, wodurch der Ressourcenverbrauch reduziert und die Gesamtleistung der Anwendung verbessert wird.

Welche Vorteile bringt die Verwendung eines CancellationToken in Hintergrunddiensten?

In Hintergrunddiensten ermöglicht die Verwendung eines CancellationToken das Management von lang andauernden Aufgaben, wie der Stapel-PDF-Verarbeitung, indem Aufgaben bei Dienstabschaltung oder während der Skalierung der Operationen sauber storniert werden können.

Wie verbessert die Integration von CancellationToken mit IronPDF die Effizienz der Anwendung?

Die Integration von CancellationToken mit IronPDF ermöglicht ein besseres Ressourcenmanagement, indem unnötige PDF-Erstellungsaufgaben storniert werden, was die Effizienz und Reaktionsfähigkeit der Anwendung verbessert, während die Serverbelastung reduziert wird.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen