在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
在现代软件开发中,高效管理长期运行的任务至关重要,尤其是在生成大型或复杂 PDF 文件的应用程序中。 C# 开发人员通常依赖 IronPDF 进行无缝 PDF 创建,但处理潜在的冗长 PDF 生成任务需要一种管理用户中断或取消的方法。
这就是在哪里取消令牌这就需要使用 C# 语言。 通过与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 软件包管理器控制台
至安装 IronPdf使用 NuGet 软件包管理器控制台,打开 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 就会添加到您的项目中。
破损图片 添加自 Pixabay,请从您的文件中选择或将图片拖放到此处。
安装 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 类)以及主要程序逻辑(程序类).
在多种实际情况下,使用一个或多个与IronPDF的取消令牌可以提高应用程序的性能和用户体验。 下面是几个例子:
在网络应用程序中,用户经常会启动一些操作,如生成 PDF 格式的报告。 但是,如果用户离开页面或关闭浏览器,系统可以检测到这一点,并使用 CancellationToken 停止 PDF 生成过程。
HttpContext.Response.RegisterForDispose(CancellationTokenSource);
HttpContext.Response.RegisterForDispose(CancellationTokenSource);
HttpContext.Response.RegisterForDispose(CancellationTokenSource)
这种简单的实现方式使网络服务器能够更有效地扩展,因为它不会将资源用于不再需要的任务。
在报告应用程序中,用户可能要求将大型数据集导出为 PDF 格式。 如果用户改变主意或进行了错误的查询,CancellationToken 允许您中途取消任务,防止资源浪费。
在后台服务或微服务中,使用CancellationToken可以更高效地管理耗时较长的任务,如生成大量 PDF 批次。 当服务即将关闭或缩减时,可以干净利落地取消正在进行的任务,确保数据不会丢失或损坏。
今天关于如何使用 IronPDF 中的 cancellationtokens 的讨论到此结束,您将能够像专业人士一样将它们应用到您的 PDF 项目中。! 使用C# CancellationToken与IronPDF您可以使用《PDF 生成工具》构建更高效、反应更灵敏的应用程序,优雅地处理 PDF 生成任务。 这种方法实现了合作取消模型,允许任务在执行过程中的安全点检查取消请求,而不是突然终止。
无论您是要管理长期运行的报告、在网络应用程序中按需生成 PDF 还是后台服务,使用 CancellationToken 或同时使用多个令牌可确保取消不必要的任务,从而避免浪费资源并增强用户体验。
只需几行代码,您就可以提高应用程序的可扩展性和响应速度,同时让用户对自己的操作拥有更多控制权。 如果您还没有了解过 IronPDF,现在正是试用的最佳时机。免费试用并了解其强大的 PDF 生成功能如何改变您的 C# 项目。