在生产环境中测试,无水印。
随时随地满足您的需求。
获得30天的全功能产品。
几分钟内就能启动并运行。
在您的产品试用期间,全面访问我们的支持工程团队。
在现代软件开发中,高效管理长期运行的任务至关重要,尤其是在生成大型或复杂 PDF 文件的应用程序中。 C# 开发人员通常依赖 IronPDF 进行无缝 PDF 创建,但处理潜在的冗长 PDF 生成任务需要一种管理用户中断或取消的方法。
这就是C#中的CancellationToken发挥作用的地方。 通过将其集成到IronPDF,您可以确保您的PDF生成任务既响应迅速又高效。 在本文中,我们将探讨 CancellationToken 的重要性、它与 IronPDF 搭配使用的原因,以及如何实现它来优雅地取消任务。
CancellationToken 是 C# 中异步编程的基本组成部分。 它允许您发出取消任务的信号,使开发人员能够更好地控制长期运行的操作。 在执行制作报告或发票等任务时,这一点会特别有帮助,因为在这些任务中,您可能希望根据数据不断生成动态报告,直到达到目标金额为止,这时您可以使用 C# 取消标记来表示应取消操作,从而优雅地结束程序。
本质上,CancellationToken 被传递给一个任务或方法,该任务或方法会定期检查是否已请求取消。 如果是这样,任务可以优雅地终止,从而释放资源并提高应用程序的响应速度。 这在生成 PDF 等情况下尤其有用,因为复杂文档的创建可能需要时间。
通过使用CancellationTokens,您可以避免任务运行时间不必要地过长带来的潜在缺点,例如浪费系统资源和不良用户体验。
在 C# 中,内部取消标记指的是在特定类或方法中创建和管理的取消标记,而不是从外部传入的。 这允许在单个组件的范围内对任务取消进行更精细的控制,使其能够监控和响应源自内部的取消请求。
在想要封装取消逻辑而不将其暴露给类的消费者,从而保持简洁界面的情况下,使用内部取消标记尤其有用。 这种方法可以增强代码的模块化,并在仍然利用更广泛的CancellationToken框架所提供的灵活性的同时,使管理复杂的异步工作流程变得更加容易。
在生成 PDF 时,尤其是在网络应用程序或复杂的报表系统中,您可能会遇到这样的情况:用户启动了一项任务,如创建一个大型 PDF 文件,但随后就离开了或不再需要结果。 在这些情况下,您需要取消 PDF 生成过程的选项,以避免对服务器或用户界面造成不必要的负载。
以下是使用CancellationToken与IronPDF的重要原因:
如果用户不再需要他们请求的 PDF,那么翻译过程就没有必要继续下去。 通过使用CancellationToken,您可以停止PDF生成任务,从而防止服务器过载并提高整体应用程序性能。
在桌面应用程序中,PDF 生成可能发生在用户界面线程上,如果任务长时间运行,可能会锁定用户界面。 通过结合CancellationToken,用户可以取消任务并保持应用程序响应。
在众多用户同时生成 PDF 的网络应用中,可扩展性是关键。 CancellationToken 允许您安全地取消不必要的任务,从而腾出资源高效地处理其他请求。
现在我们了解了CancellationToken为什么有用,我们来演示如何在IronPDF中实现它。
要开始使用IronPDF,您首先需要安装它。 如果已经安装,则可以跳到下一节,否则,以下步骤将介绍如何安装 IronPDF 库。
通过 NuGet 包管理器控制台
要使用 NuGet 包管理器控制台安装 IronPDF,请打开 Visual Studio 并导航到包管理器控制台。 然后运行以下命令:
Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
通过解决方案的NuGet包管理器
打开 Visual Studio,进入 "工具 -> NuGet 包管理器 -> 管理解决方案的 NuGet 包 "并搜索 IronPdf。 在这里,您只需选择您的项目并点击 "安装",IronPDF 就会添加到您的项目中。
-->安装 IronPDF 后,只需在代码顶部添加正确的 using 语句即可开始使用 IronPDF:
using IronPdf;
using IronPdf;
Imports IronPdf
让我们深入了解实际执行情况。 在此示例中,我们将使用IronPDF从HTML生成一个简单的PDF,但同时使用CancellationToken,以便在必要时取消任务。
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
控制台输出
PDF 输出
在这个例子中,我们演示了如何在C#程序中使用CancellationToken来取消使用IronPDF的长时间运行的PDF生成任务。 代码分为两部分:PDF生成过程(PdfGenerator类)和主程序逻辑(Program类)。
在多个实际情况下,使用一个或多个取消令牌与IronPDF结合可以提升应用程序的性能和用户体验。 下面是几个例子:
在网络应用程序中,用户经常会启动一些操作,如生成 PDF 格式的报告。 但是,如果用户离开页面或关闭浏览器,系统可以检测到这一点并使用CancellationToken来停止PDF生成过程。
HttpContext.Response.RegisterForDispose(CancellationTokenSource);
HttpContext.Response.RegisterForDispose(CancellationTokenSource);
HttpContext.Response.RegisterForDispose(CancellationTokenSource)
这种简单的实现方式使网络服务器能够更有效地扩展,因为它不会将资源用于不再需要的任务。
在报告应用程序中,用户可能要求将大型数据集导出为 PDF 格式。 如果用户改变主意或发出错误的查询,CancellationToken允许您在中途取消任务,防止资源浪费。
在后台服务或微服务中,可以使用CancellationToken来更有效地管理需要大量时间的任务,例如生成大型PDF批次。 当服务即将关闭或缩减时,可以干净利落地取消正在进行的任务,确保数据不会丢失或损坏。
现在我们已经结束了今天关于在IronPDF中使用CancellationToken的讨论,您将能够像专业人士一样将它们应用到您的PDF项目中! 使用C# CancellationToken与IronPDF结合,能够让您构建更加高效、响应迅速的应用程序,优雅地处理PDF生成任务。 这种方法实现了合作取消模型,允许任务在执行过程中的安全点检查取消请求,而不是突然终止。
无论您是在管理长时间运行的报告、按需在 Web 应用程序中生成 PDF,还是在后台服务中进行操作,使用CancellationToken或同时使用多个令牌可以确保取消不必要的任务,从而防止资源浪费并提升用户体验。
只需几行代码,您就可以提高应用程序的可扩展性和响应速度,同时让用户对自己的操作拥有更多控制权。 如果您还没有探索过IronPDF,现在是尝试免费试用的最佳时机,了解其强大的PDF生成功能如何能改变您的C#项目。