使用 IRON SUITE

使用 Iron Software 库中的 C# CancellationToken

现代 .NET 开发人员在集成 IronPDFIronOCRIronWordIronXL 等库时经常使用异步编程。 这些产品经常运行长时间运行的任务,如渲染 PDF、处理 OCR 内容或生成大型电子表格,而保持应用程序响应速度的正确方法是使用基于 C# CancellationToken 的取消。

本文介绍了如何使用 取消令牌、方法如何接受令牌、如何处理任务取消,以及如何将这些模式与 Iron Software 库进行适当、及时的集成。 我们还将介绍最佳实践、资源管理以及如何同时使用多个 CancellationTokens。

为什么取消请求在 Iron 软件工作量中很重要

IronSoftware

Iron Software 工具经常运行异步操作--例如:

这些可能是长期运行的操作,必须在用户点击取消按钮、导航离开或调用代码发出 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;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

标记使用方法参数向下传递:

public async Task ProcessPdfAsync(string html, CancellationToken token)
public async Task ProcessPdfAsync(string html, CancellationToken token)
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

在该方法中,您将定期检查

token.ThrowIfCancellationRequested();
token.ThrowIfCancellationRequested();
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

或检查 IsCancellationRequested 属性:

if (token.IsCancellationRequested)
{
    Console.WriteLine("Cancellation requested.");
    return;
}
if (token.IsCancellationRequested)
{
    Console.WriteLine("Cancellation requested.");
    return;
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

这提供了一种合作取消模式,只有当您的代码检查标记时,才会发生操作取消事件。

在 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);
    }
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

控制台输出示例

 控制台输出

这是一个支持在多个点取消的公共异步任务。 当取消操作时,方法会抛出 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);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

示例输出

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
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

这样可以确保取消请求得到及时、适当的处理,并且系统不会浪费周期。

在 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);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

这样可以确保如果用户导航离开,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);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

这是服务器端长期运行任务的一般模式。

使用 Iron 软件取消标记的最佳实践

  • 始终在异步方法中传递 CancellationToken。

  • 在循环中使用 ThrowIfCancellationRequested。

  • 优先选择等待 Task.Delay,而不是紧密循环。

  • 使用 LinkedTokenSource 组合令牌。

  • 始终处理 OperationCanceledException。

  • 使用取消功能可以更好地管理资源和响应应用程序。

  • 请记住,C# 是一种面向对象的编程语言,因此要干净利落地设计取消方法和取消逻辑。

任务取消的高级考虑因素

为确保这篇文章适合任何 .NET 开发人员阅读,这里有一个简短的补充部分,其中包含了其余相关术语,同时强化了最佳实践。

C# 中的任务取消不是自动的; 这取决于在您的方法中实现的取消逻辑。 必须检查令牌属性,返回给消费者的令牌应允许他们确定操作是已取消还是已成功完成。 如果请求无法完成,系统仍应以适当和及时的方式优雅地终止请求。

如果用户界面触发了取消按钮,CancellationTokenSource 上的 cancel 方法将发出取消信号,您的代码应定期通过 token.IsCancellationRequested 进行检查。 当操作取消事件发生时,您将释放资源并将控制权返回给调用者。

IronOCR 扫描深嵌套文档或 IronXL 生成海量电子表格这样的长期运行操作,应在每一层都传递 CancellationToken 。 当用户离开页面时,操作应干净利落地结束。

Iron Software 产品原生遵循 .NET 异步编程模型,因此翻译起来更加容易。 在编写您自己的库时,请考虑遵循相同的最佳实践,以便您的用户可以及时取消操作,而不会泄露内存或占用未管理的资源。

结论

将 C# CancellationToken 与 IronPDFIronOCRIronWordIronXL 结合使用可提供一种合作取消方法,使应用程序保持响应、高效和稳健。通过应用异步编程中的最佳实践、向异步任务传递标记和定期检查取消,您可以构建更快、更安全和更可维护的 .NET 应用程序,并在需要时优雅地终止。