使用 Iron 軟體函式庫的 C# CancellationToken
現代.NET開發人員在整合IronPDF 、 IronOCR 、 IronWord和IronXL等程式庫時經常使用非同步程式設計。 這些產品經常運行長時間運行的任務,例如渲染 PDF、處理 OCR 內容或生成大型電子表格,而保持應用程式回應的正確方法是使用基於 C# CancellationToken 的取消功能。
本文說明如何使用取消令牌、方法如何接受令牌、如何處理任務取消,以及如何以適當且及時的方式將這些模式與Iron Software庫整合。 我們還將介紹最佳實踐、資源管理以及如何同時使用多個取消令牌。
為什麼取消要求對Iron Software工作負載至關重要

Iron Software工具通常會執行非同步操作,例如:
- IronPDF HTML 轉 PDF 功能
- IronOCR長期運作的OCR 提取
- 在後台服務中建置的IronWord或IronXL文檔
- 在產生 PDF 之前,需要向 HttpClient 發送一個大型 Web 請求
這些操作可能是長時間運行的操作,當使用者點擊"取消"按鈕、離開頁面或呼叫程式碼發出取消請求時,這些操作必須優雅地終止。
使用取消令牌可確保:
- 響應式應用程式
- 更完善的資源管理
- 控制釋放未託管資源
- 一個乾淨的合作取消模型
了解 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
這提供了一種協作式取消模式,其中操作取消事件僅在您的程式碼檢查令牌時發生。
將 CancellationToken 與IronPDF結合使用
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 區塊中處理該例外狀況。
將 CancellationToken 與IronOCR結合使用
IronOCR 長期運作的影像掃描功能也受益於內部取消代幣:
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 之前,如果要透過 Web 請求取得 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後台服務包含一個內部 CancellationToken,該令牌會自動傳遞給 ExecuteAsync 方法。 運行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 Software的取消令牌的最佳實踐
-
始終將 CancellationToken 傳遞給非同步方法。
-
在循環中使用 ThrowIfCancellationRequested。
-
建議使用 await Task.Delay 而不是緊密的循環。
-
將令牌與 LinkedTokenSource 合併。
-
始終處理 OperationCanceledException 例外。
-
使用取消功能可以更好地管理資源並提高應用程式的回應速度。
- 請記住,C# 是一種物件導向的程式語言,因此請清楚地設計您的取消方法和取消邏輯。
任務取消的高階考慮因素
為了確保本文對任何.NET開發人員都有幫助,以下是一個簡短的補充部分,其中包含了仍然相關的術語,同時強化了最佳實踐。
C# 中的任務取消不是自動的; 這取決於你的方法內部實作的取消邏輯。 必須檢查令牌屬性,並且傳回給消費者的令牌應該允許他們確定操作是已取消還是已成功完成。 如果請求無法完成,系統仍應以適當且及時的方式優雅地終止。
如果使用者介面觸發了取消按鈕,則 CancellationTokenSource 上的 cancel 方法將發出取消訊號,並且您的程式碼應定期透過 token.IsCancellationRequested 檢查。 當操作取消事件發生時,您將釋放資源並將控制權傳回給呼叫者。
像IronOCR掃描深度嵌套文件或IronXL產生大型電子表格這樣的長時間運行的操作,應該在每一層都傳遞CancellationToken 。 當使用者離開頁面時,操作應該正常結束。
Iron Software產品讓這一切變得更加容易,因為它們原生遵循.NET非同步程式設計模型。 編寫自己的程式庫時,請考慮遵循相同的最佳實踐,以便您的用戶能夠及時取消操作,而不會造成記憶體洩漏或佔用未管理的資源。
結論
將 C# CancellationToken 與IronPDF 、 IronOCR 、 IronWord和IronXL結合使用,可提供一種協作式取消機制,從而保持應用程式的反應速度、效率和健全性。透過應用非同步程式設計的最佳實踐、將令牌傳遞給非同步任務以及定期檢查取消狀態,您可以建立速度更快、更安全、更易於維護的.NET應用程序,並在需要時優雅地終止它們。