使用 Iron 軟體函式庫的 C# CancellationToken
現代的 .NET 開發人員在整合 IronPDF、IronOCR、IronWord、IronXL等函式庫時,經常會使用異步程式設計。 這些產品經常執行長時間運行的任務,例如渲染 PDF、處理 OCR 內容或產生大型試算表,而保持應用程式反應迅速的正確方法是使用 C# CancellationToken 為基礎的取消。
本文將解釋如何使用 取消令牌、方法如何接受令牌、如何處理任務取消,以及如何適當且及時地將這些模式與 Iron Software 函式庫整合。 我們也會涵蓋最佳實務、資源管理,以及如何同時使用多個 CancellationTokens。
為什麼取消請求在 Iron 軟體工作量中很重要。
Iron Software 工具經常執行異步操作 - 例如:
- IronPDF HTML-to-PDF轉換。
- IronOCR 長期執行的 OCR 抽取。
- 在 Background Services 內建立 IronWord 或 IronXL 文件。
- 生成 PDF 前的大型 HttpClient 網頁請求
這些可能是長時間執行的作業,必須在使用者按下取消按鈕、導航離開或呼叫程式碼發出 CancellationRequest 時優雅地終止。
使用取消代幣可確保:
- 回應式應用程式
- 更好的資源管理
- 非管理資源的受控釋出
- 乾淨的合作取消模式
瞭解 C# CancellationToken 基礎知識
C# 提供 CancellationTokenSource 類別,可建立 CancellationToken 令牌。 CTS new CancellationTokenSource() 可以建立一個傳給 async 方法的 token。
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控制台輸出範例

這顯示了一個支援在多點取消的公共 async 任務。 當取消發生時,方法會拋出 OperationCanceledException,您可以在 catch 區塊中處理。
使用 IronOCR 的 CancellationToken。
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範例輸出

IronWord 文件生成和 IronXL 電子表格組裝的工作方式相同。 由於這些都是可取消的作業,合作取消模式可避免阻塞 UI 線程或背景服務。
在長操作中定期檢查取消。
常見的模式是循環和檢查取消:
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 軟體取消代幣的最佳實務
請務必在 async 方法中傳入 CancellationToken。
在循環內使用 ThrowIfCancellationRequested。
偏好等待 Task.Delay,而非緊密循環。
結合 LinkedTokenSource 的代幣。
永遠處理 OperationCanceledException。
使用取消功能以獲得更好的資源管理和反應迅速的應用程式。
- 請記住 C# 是一種物件導向的程式語言,因此請乾淨地設計您的取消方法和取消邏輯。
取消任務的進階考量
為了確保這是一篇適合任何 .NET 開發人員閱讀的文章,這裡有一個簡短的補充部分,在強化最佳實務的同時,也納入了其他相關的術語。
C# 中的任務取消並非自動執行; 這取決於在您的方法中執行的取消邏輯。 必須檢查 token 屬性,而返回給消費者的 token 應該能讓他們判斷操作是否已取消或成功完成。 如果請求無法完成,系統仍應以適當且及時的方式優雅地終止。
如果使用者介面觸發取消按鈕,您的 CancellationTokenSource 上的 cancel 方法將發出取消信號,您的程式碼應定期透過 token.IsCancellationRequested 進行檢查。 當操作取消事件發生時,您會釋放資源並將控制權交回呼叫者。
像 IronOCR 掃描深層嵌套的文件或 IronXL 產生大量試算表這樣長時間運行的作業,應該在每一層都傳送 CancellationToken 。 當使用者瀏灠頁面時,操作應該乾淨地結束。
Iron Software 產品原生遵循 .NET 異步程式設計模型,因此能讓這件事變得更容易。 在撰寫您自己的函式庫時,請考慮遵循相同的最佳實務,讓您的消費者可以及時取消作業,而不會洩漏記憶體或佔用未管理的資源。
結論
將 C# CancellationToken 與IronPDF 、 IronOCR 、 IronWord和IronXL結合使用,可提供一種協作式取消機制,從而保持應用程式的反應速度、效率和健全性。透過應用非同步編程的最佳實踐、將令牌傳遞給非同步任務以及定期檢查取消狀態,您可以建立速度更快、更安全、更易於維護的 .NET 應用程序,並在需要時優雅地終止它們。