Iron Suite for .NET
10 .NETライブラリ。1つの完全なドキュメントスイート。
.NET 10でHTMLをPDFに変換する方法
現代 for .NET開発者は、IronPDF、IronOCR、IronWord、IronXLのようなライブラリを統合するとき、非同期プログラミングを頻繁に利用します。 これらの製品は、PDFのレンダリング、OCRコンテンツの処理、大規模なスプレッドシートの生成といった長時間実行されるタスクを頻繁に実行します。そして、アプリケーションを応答性のある状態に保つための正しい方法は、C#のCancellationTokenベースのキャンセルを使用することです。
この記事では、キャンセル・トークンの使用方法、メソッドがトークンを受け入れる方法、タスク・キャンセルの処理方法、これらのパターンを適切かつタイムリーにIron Softwareライブラリと統合する方法について説明します。 また、ベストプラクティス、リソース管理、複数のCancellationTokensを同時に使用する方法についても説明します。
Iron Softwareのワークロードにおけるキャンセル要求の重要性

Iron Softwareのツールは、非同期処理を実行することがよくあります:
- IronPDF HTMLからPDFへの変換
- IronOCRの長時間実行されるOCR抽出
- IronWordまたはIronXLドキュメントのバックグラウンドサービス内での生成
- PDF生成前の大きなHttpClientウェブリクエスト
これらは、ユーザーがキャンセルボタンをクリックしたり、移動したり、呼び出しコードがキャンセル要求を発行したときに、スムーズに終了する必要がある長時間実行される操作です。
キャンセルトークンを使用することで、確実になります:
- レスポンシブアプリケーション
- リソース管理の改善
- 管理されていないリソースの制御されたリリース
- クリーンな協調キャンセルモデル
C# CancellationTokenの基本について理解する
C# は、CancellationToken トークンを作成する CancellationTokenSource クラスを提供します。 CTS new CancellationTokenSource() は、非同期メソッドに渡されるトークンを作成できます。
var cts = new CancellationTokenSource();
CancellationToken token = cts.Token;Dim cts As New CancellationTokenSource()
Dim token As CancellationToken = cts.TokenDim 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 TaskPublic Async Function ProcessPdfAsync(html As String, token As CancellationToken) As Taskメソッド内では、定期的にチェックを行います:
token.ThrowIfCancellationRequested();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 IfIf 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 ClassImports 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 をスローします。
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 ClassImports 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スレッドやBackground Servicesのブロックを回避します。
長い操作のキャンセルを定期的にチェックする
よくあるパターンは、ループとキャンセルチェックです:
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 FunctionImports 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レンダリングの前にCancellationTokenをHttpClientで使う
PDF を生成する前に HTML を取得する Web リクエストを実行するときは、常にトークンを渡してください:
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 FunctionImports 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コアのバックグラウンド サービスにおけるキャンセル
.NET Coreバックグラウンドサービスには、ExecuteAsyncメソッドに自動的に渡される内部CancellationTokenが含まれています。 Ironソフトウェアのツールを実行するときに使用してください:
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 FunctionProtected 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の非同期プログラミングモデルにネイティブに準拠しているため、翻訳が容易です。 独自のライブラリを書く際には、同じベストプラクティスに従うことを検討してください。そうすることで、コンシューマは、メモリをリークしたり、管理されていないリソースを保持したりすることなく、タイムリーに操作をキャンセルすることができます。
結論
IronPDF、IronOCR、IronWord、IronXLでC#のCancellationTokenを使用することは、アプリケーションを応答性が高く、効率的で、堅牢に保つ共同キャンセルアプローチを提供します。非同期プログラミングのベストプラクティスを適用し、非同期タスクにトークンを渡し、定期的にキャンセルをチェックすることで、必要に応じてスムーズに終了する、より速く、安全で、メンテナンスしやすい.NETアプリケーションを構築できます。