使用 Iron Software 库中的 C# CancellationToken
现代 .NET 开发人员在集成 IronPDF、IronOCR、IronWord 和 IronXL 等库时经常使用异步编程。 这些产品经常运行长时间运行的任务,如渲染 PDF、处理 OCR 内容或生成大型电子表格,而保持应用程序响应速度的正确方法是使用基于 C# CancellationToken 的取消。
本文介绍了如何使用 取消令牌、方法如何接受令牌、如何处理任务取消,以及如何将这些模式与 Iron Software 库进行适当、及时的集成。 我们还将介绍最佳实践、资源管理以及如何同时使用多个 CancellationTokens。
为什么取消请求在 Iron 软件工作量中很重要
Iron Software 工具经常运行异步操作--例如:
- IronPDF HTML 到 PDF 的转换。
- IronOCR 长期运行的 OCR 提取。
- 在后台服务中构建 IronWord 或 IronXL 文档。
- 生成 PDF 之前的大型 HttpClient 网络请求
这些可能是长期运行的操作,必须在用户点击取消按钮、导航离开或调用代码发出 CancellationRequest 时优雅地终止。
使用取消标记可确保:
- 响应式应用程序
- 更好的资源管理
- 非托管资源的可控发布
- 简洁的合作取消模式
了解 C# CancellationToken 基础知识
C# 提供了 CancellationTokenSource 类,用于创建 CancellationToken 标记。 CTS new CancellationTokenSource() 可以创建传递给异步方法的令牌。
var cts = new CancellationTokenSource();
CancellationToken token = cts.Token;var cts = new CancellationTokenSource();
CancellationToken token = cts.Token;Dim cts As New CancellationTokenSource()
Dim token As CancellationToken = cts.Token标记使用方法参数向下传递:
public async Task ProcessPdfAsync(string html, CancellationToken token)public async Task ProcessPdfAsync(string html, CancellationToken token)Public Async Function ProcessPdfAsync(html As String, token As CancellationToken) As Task在该方法中,您将定期检查
token.ThrowIfCancellationRequested();token.ThrowIfCancellationRequested();token.ThrowIfCancellationRequested()或检查 IsCancellationRequested 属性:
if (token.IsCancellationRequested)
{
Console.WriteLine("Cancellation requested.");
return;
}if (token.IsCancellationRequested)
{
Console.WriteLine("Cancellation requested.");
return;
}If token.IsCancellationRequested Then
Console.WriteLine("Cancellation requested.")
Return
End If这提供了一种合作取消模式,只有当您的代码检查标记时,才会发生操作取消事件。
在 IronPDF 中使用 CancellationToken.
IronPDF 的HTML 渲染专为异步编程而设计,因此您可以自然地集成取消。
public async Task<PdfDocument> BuildPdfAsync(string html, CancellationToken token)
{
Console.WriteLine("\n[Generator] Starting PDF rendering process...");
var renderer = new ChromePdfRenderer();
token.ThrowIfCancellationRequested();
Console.WriteLine("[Generator] Simulating a 2-second delay...");
await Task.Delay(2000, token);
token.ThrowIfCancellationRequested();
Console.WriteLine("[Generator] Delay complete. Starting actual rendering...");
// This is the working overload for your library version
return await renderer.RenderHtmlAsPdfAsync(html);
}public async Task<PdfDocument> BuildPdfAsync(string html, CancellationToken token)
{
Console.WriteLine("\n[Generator] Starting PDF rendering process...");
var renderer = new ChromePdfRenderer();
token.ThrowIfCancellationRequested();
Console.WriteLine("[Generator] Simulating a 2-second delay...");
await Task.Delay(2000, token);
token.ThrowIfCancellationRequested();
Console.WriteLine("[Generator] Delay complete. Starting actual rendering...");
// This is the working overload for your library version
return await renderer.RenderHtmlAsPdfAsync(html);
}Imports System
Imports System.Threading
Imports System.Threading.Tasks
Public Class PdfGenerator
Public Async Function BuildPdfAsync(html As String, token As CancellationToken) As Task(Of PdfDocument)
Console.WriteLine(vbCrLf & "[Generator] Starting PDF rendering process...")
Dim renderer As New ChromePdfRenderer()
token.ThrowIfCancellationRequested()
Console.WriteLine("[Generator] Simulating a 2-second delay...")
Await Task.Delay(2000, token)
token.ThrowIfCancellationRequested()
Console.WriteLine("[Generator] Delay complete. Starting actual rendering...")
' This is the working overload for your library version
Return Await renderer.RenderHtmlAsPdfAsync(html)
End Function
End Class控制台输出示例

这是一个支持在多个点取消的公共异步任务。 当取消操作时,方法会抛出 OperationCanceledException,您可以在 catch 块中处理该异常。
使用 IronOCR 取消令牌
IronOCR 长期运行的扫描图像操作也得益于内部的 CancellationToken:
public class OcrProcessor
{
private readonly IronOcr.IronTesseract ocr = new IronOcr.IronTesseract();
public async Task<string> ExtractTextAsync(string path, CancellationToken token)
{
// Check for cancellation immediately upon entering the method.
token.ThrowIfCancellationRequested();
// Run the synchronous OCR method on a background thread.
// This is the correct pattern for cancellable synchronous wrappers.
return await Task.Run(() => ocr.Read(path).Text, token);
}
}public class OcrProcessor
{
private readonly IronOcr.IronTesseract ocr = new IronOcr.IronTesseract();
public async Task<string> ExtractTextAsync(string path, CancellationToken token)
{
// Check for cancellation immediately upon entering the method.
token.ThrowIfCancellationRequested();
// Run the synchronous OCR method on a background thread.
// This is the correct pattern for cancellable synchronous wrappers.
return await Task.Run(() => ocr.Read(path).Text, token);
}
}Imports System.Threading
Imports System.Threading.Tasks
Imports IronOcr
Public Class OcrProcessor
Private ReadOnly ocr As New IronTesseract()
Public Async Function ExtractTextAsync(path As String, token As CancellationToken) As Task(Of String)
' Check for cancellation immediately upon entering the method.
token.ThrowIfCancellationRequested()
' Run the synchronous OCR method on a background thread.
' This is the correct pattern for cancellable synchronous wrappers.
Return Await Task.Run(Function() ocr.Read(path).Text, token)
End Function
End Class示例输出
!IronOCR 与 CancellationTokens 的使用示例。
IronWord 文档生成和 IronXL 电子表格组装的工作方式相同。 由于这些都是可取消的操作,合作取消模式避免了阻塞用户界面线程或后台服务。
定期检查长操作中的取消操作
常见的模式是循环和检查取消:
public async Task LongRunningOperation(CancellationToken token)
{
for (int i = 0; i < 1000; i++)
{
token.ThrowIfCancellationRequested();
await Task.Delay(10, token); // await Task.Delay helps cooperative cancellation
}
}public async Task LongRunningOperation(CancellationToken token)
{
for (int i = 0; i < 1000; i++)
{
token.ThrowIfCancellationRequested();
await Task.Delay(10, token); // await Task.Delay helps cooperative cancellation
}
}Imports System.Threading
Imports System.Threading.Tasks
Public Async Function LongRunningOperation(token As CancellationToken) As Task
For i As Integer = 0 To 999
token.ThrowIfCancellationRequested()
Await Task.Delay(10, token) ' Await Task.Delay helps cooperative cancellation
Next
End Function这样可以确保取消请求得到及时、适当的处理,并且系统不会浪费周期。
在 IronPDF 渲染之前使用 HttpClient 的 CancellationToken.
在生成 PDF 之前执行网络请求获取 HTML 时,请务必传递令牌:
var client = new HttpClient();
public async Task<string> FetchHtmlAsync(string url, CancellationToken token)
{
var response = await client.GetAsync(url, token);
if (!response.IsSuccessStatusCode)
throw new Exception("Error occurred while requesting content.");
return await response.Content.ReadAsStringAsync(token);
}var client = new HttpClient();
public async Task<string> FetchHtmlAsync(string url, CancellationToken token)
{
var response = await client.GetAsync(url, token);
if (!response.IsSuccessStatusCode)
throw new Exception("Error occurred while requesting content.");
return await response.Content.ReadAsStringAsync(token);
}Imports System.Net.Http
Imports System.Threading
Imports System.Threading.Tasks
Dim client As New HttpClient()
Public Async Function FetchHtmlAsync(url As String, token As CancellationToken) As Task(Of String)
Dim response = Await client.GetAsync(url, token)
If Not response.IsSuccessStatusCode Then
Throw New Exception("Error occurred while requesting content.")
End If
Return Await response.Content.ReadAsStringAsync(token)
End Function这样可以确保如果用户导航离开,HttpClient 会及时取消。
.NET Core 后台服务中的取消
.NET Core 后台服务包括一个自动传递给 ExecuteAsync 方法的内部 CancellationToken。 运行 Iron Software 工具时使用:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await ProcessPdfAsync("<h1>Hello</h1>", stoppingToken);
await Task.Delay(5000, stoppingToken);
}
}protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await ProcessPdfAsync("<h1>Hello</h1>", stoppingToken);
await Task.Delay(5000, stoppingToken);
}
}Protected Overrides Async Function ExecuteAsync(stoppingToken As CancellationToken) As Task
While Not stoppingToken.IsCancellationRequested
Await ProcessPdfAsync("<h1>Hello</h1>", stoppingToken)
Await Task.Delay(5000, stoppingToken)
End While
End Function这是服务器端长期运行任务的一般模式。
使用 Iron 软件取消标记的最佳实践
始终在异步方法中传递 CancellationToken。
在循环中使用 ThrowIfCancellationRequested。
优先选择等待 Task.Delay,而不是紧密循环。
使用 LinkedTokenSource 组合令牌。
始终处理 OperationCanceledException。
使用取消功能可以更好地管理资源和响应应用程序。
- 请记住,C# 是一种面向对象的编程语言,因此要干净利落地设计取消方法和取消逻辑。
任务取消的高级考虑因素
为确保这篇文章适合任何 .NET 开发人员阅读,这里有一个简短的补充部分,其中包含了其余相关术语,同时强化了最佳实践。
C# 中的任务取消不是自动的; 这取决于在您的方法中实现的取消逻辑。 必须检查令牌属性,返回给消费者的令牌应允许他们确定操作是已取消还是已成功完成。 如果请求无法完成,系统仍应以适当和及时的方式优雅地终止请求。
如果用户界面触发了取消按钮,CancellationTokenSource 上的 cancel 方法将发出取消信号,您的代码应定期通过 token.IsCancellationRequested 进行检查。 当操作取消事件发生时,您将释放资源并将控制权返回给调用者。
像 IronOCR 扫描深嵌套文档或 IronXL 生成海量电子表格这样的长期运行操作,应在每一层都传递 CancellationToken 。 当用户离开页面时,操作应干净利落地结束。
Iron Software 产品原生遵循 .NET 异步编程模型,因此翻译起来更加容易。 在编写您自己的库时,请考虑遵循相同的最佳实践,以便您的用户可以及时取消操作,而不会泄露内存或占用未管理的资源。
结论
将 C# CancellationToken 与IronPDF 、 IronOCR 、 IronWord和IronXL结合使用,可以提供一种协作式取消机制,从而保持应用程序的响应速度、效率和健壮性。通过应用异步编程的最佳实践、将令牌传递给异步任务以及定期检查取消状态,您可以构建速度更快、更安全、更易于维护的 .NET 应用程序,并在需要时优雅地终止它们。