在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
在現代軟體開發中,高效管理長時間運行的任務是關鍵,特別是在需要生成大型或複雜 PDF 文件的應用程式中。 C# 開發人員經常依賴 IronPDF 進行無縫的 PDF 創建,但處理可能冗長的 PDF 生成任務需要一種管理用戶中斷或取消的方法。
這就是 C# 中的 CancellationToken 派上用場的地方。 通過與IronPDF整合,您可以確保您的 PDF 生成功能既具應用性又有效率。 在本文中,我們將探討 CancellationToken 的重要性,為什麼它與 IronPDF 很搭配,以及如何實施它以優雅地取消任務。
CancellationToken 是 C# 中非同步程式設計的基本部分。 它允許您表明應取消的任務,從而使開發人員對長時間運行的操作有更大的控制權。 這在執行生成報告或發票等任務時特別有用。您可能希望從數據中不斷生成動態報告,直到達到目標數量,然後您可以使用 C# 取消權杖來指示應取消操作,從而優雅地結束程序。
基本上,CancellationToken 會傳遞給任務或方法,這些任務或方法會定期檢查是否已經請求取消。 如果是這樣,該任務可以優雅地終止,釋放資源並提高應用程式的響應能力。 這在 PDF 生成的情況下特別有用,因為複雜的文件可能需要一些時間來創建。
透過使用CancellationTokens,您可以避免任務不必要地長時間執行所帶來的潛在缺點,例如浪費系統資源和不良的用戶體驗。
在C#中,內部取消權杖是指在特定類別或方法內創建和管理的取消權杖,而不是從外部來源傳入的。 這允許在單個組件範圍內更精細地控制任務取消,使其能夠監控和響應內部發起的取消請求。
使用內部取消令牌特別適用於您希望封裝取消邏輯而不向類的使用者暴露的情況,從而保持介面的清晰。 這種方法可以增強程式碼的模組化,使管理複雜的異步工作流變得更加容易,同時仍然利用更廣泛的CancellationToken框架所提供的靈活性。
在生成 PDF 時,特別是在網絡應用程序或複雜報告系統中,您可能會遇到這樣的情況:使用者啟動任務(如創建大型 PDF 檔案),但隨後導航離開或不再需要結果。 在這些情況下,您希望有取消 PDF 生成功能的選項,以避免對伺服器或用戶界面造成不必要的負擔。
使用CancellationToken與IronPDF的原因如下:
如果使用者不再需要他們要求的 PDF,那麼這個流程就沒有理由繼續。 通過利用CancellationToken,您可以停止 PDF 生成任務,防止對伺服器的過度負載並改善整體應用程式性能。
在桌面應用程式中,PDF 生成可能發生在 UI 執行緒上,若任務執行時間較長,可能會鎖住使用者介面。 透過整合CancellationToken,使用者可以取消任務並保持應用程式的響應性。
在許多用戶同時生成 PDF 的網路應用程式中,可擴展性是關鍵。 CancellationToken 讓你可以安全地取消不必要的任務,從而釋放資源以高效地處理其他請求。
既然我們了解為什麼CancellationToken很有用,那麼讓我們一起看看如何在IronPDF中實現它。
要開始使用IronPDF,您首先需要安裝它。 如果已經安裝,則可以跳到下一部分。否則,以下步驟將介紹如何安裝IronPDF庫。
通過 NuGet 套件管理器控制台
若要使用 NuGet 套件管理器主控台安裝 IronPDF,請開啟 Visual Studio 並導航至套件管理器主控台。 然後執行以下命令:
Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
通過解決方案的 NuGet 套件管理器
打開 Visual Studio,前往「工具 -> NuGet 套件管理員 -> 為方案管理 NuGet 套件」並搜尋 IronPDF。 從這裡開始,您只需選擇您的專案並點擊「安裝」,IronPDF 就會被添加到您的專案中。
安裝 IronPDF 後,您只需在程式碼的頂部新增正確的 using 語句即可開始使用 IronPDF:
using IronPdf;
using IronPdf;
Imports IronPdf
讓我們深入實際的實施。 在此範例中,我們將使用IronPDF從HTML生成簡單的PDF,但同時使用CancellationToken以便在必要時取消任務。
using IronPdf;
using System;
using System.Threading;
using System.Threading.Tasks;
public class PdfGenerator
{
public async Task GeneratePdfWithCancellation(CancellationToken token)
{
var Renderer = new ChromePdfRenderer();
try
{
// Check for cancellation before starting
token.ThrowIfCancellationRequested();
// Simulating a long task that can be checked for cancellation periodically
for (int i = 0; i < 10; i++)
{
// Simulating a piece of work (this could be part of a larger HTML rendering)
await Task.Delay(500); // Simulate chunk processing
// Periodically check for cancellation in long-running operations
if (token.IsCancellationRequested)
{
Console.WriteLine("Cancellation requested. Throwing exception.");
token.ThrowIfCancellationRequested(); // This will trigger an OperationCanceledException
}
}
// Simulate PDF creation after the long process
var pdf = await Renderer.RenderHtmlAsPdfAsync("<h1>Hello, PDF!</h1>");
// Save the PDF after ensuring no cancellation occurred
pdf.SaveAs("output.pdf");
Console.WriteLine("PDF generated successfully.");
}
catch (OperationCanceledException)
{
// Handle task cancellation
Console.WriteLine("PDF generation was canceled.");
}
catch (Exception ex)
{
// Handle other exceptions
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
public class Program
{
public static async Task Main(string[] args)
{
// Create a CancellationTokenSource
var cancellationTokenSource = new CancellationTokenSource();
// Creating our one cancellation token
var token = cancellationTokenSource.Token;
// Start the PDF generation task
var pdfGenerator = new PdfGenerator();
Task pdfTask = pdfGenerator.GeneratePdfWithCancellation(token);
// Simulate a cancellation scenario
Console.WriteLine("Press any key to cancel PDF generation...");
Console.ReadKey();
// Cancel the task by calling Cancel() on the CancellationTokenSource
cancellationTokenSource.Cancel();
try
{
// Await the task to handle any exceptions, such as cancellation
await pdfTask;
}
catch (OperationCanceledException)
{
// Confirm the cancellation
Console.WriteLine("The PDF generation was canceled.");
}
finally
{
cancellationTokenSource.Dispose();
}
Console.WriteLine("Program finished.");
}
}
using IronPdf;
using System;
using System.Threading;
using System.Threading.Tasks;
public class PdfGenerator
{
public async Task GeneratePdfWithCancellation(CancellationToken token)
{
var Renderer = new ChromePdfRenderer();
try
{
// Check for cancellation before starting
token.ThrowIfCancellationRequested();
// Simulating a long task that can be checked for cancellation periodically
for (int i = 0; i < 10; i++)
{
// Simulating a piece of work (this could be part of a larger HTML rendering)
await Task.Delay(500); // Simulate chunk processing
// Periodically check for cancellation in long-running operations
if (token.IsCancellationRequested)
{
Console.WriteLine("Cancellation requested. Throwing exception.");
token.ThrowIfCancellationRequested(); // This will trigger an OperationCanceledException
}
}
// Simulate PDF creation after the long process
var pdf = await Renderer.RenderHtmlAsPdfAsync("<h1>Hello, PDF!</h1>");
// Save the PDF after ensuring no cancellation occurred
pdf.SaveAs("output.pdf");
Console.WriteLine("PDF generated successfully.");
}
catch (OperationCanceledException)
{
// Handle task cancellation
Console.WriteLine("PDF generation was canceled.");
}
catch (Exception ex)
{
// Handle other exceptions
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
public class Program
{
public static async Task Main(string[] args)
{
// Create a CancellationTokenSource
var cancellationTokenSource = new CancellationTokenSource();
// Creating our one cancellation token
var token = cancellationTokenSource.Token;
// Start the PDF generation task
var pdfGenerator = new PdfGenerator();
Task pdfTask = pdfGenerator.GeneratePdfWithCancellation(token);
// Simulate a cancellation scenario
Console.WriteLine("Press any key to cancel PDF generation...");
Console.ReadKey();
// Cancel the task by calling Cancel() on the CancellationTokenSource
cancellationTokenSource.Cancel();
try
{
// Await the task to handle any exceptions, such as cancellation
await pdfTask;
}
catch (OperationCanceledException)
{
// Confirm the cancellation
Console.WriteLine("The PDF generation was canceled.");
}
finally
{
cancellationTokenSource.Dispose();
}
Console.WriteLine("Program finished.");
}
}
Imports IronPdf
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Public Class PdfGenerator
Public Async Function GeneratePdfWithCancellation(ByVal token As CancellationToken) As Task
Dim Renderer = New ChromePdfRenderer()
Try
' Check for cancellation before starting
token.ThrowIfCancellationRequested()
' Simulating a long task that can be checked for cancellation periodically
For i As Integer = 0 To 9
' Simulating a piece of work (this could be part of a larger HTML rendering)
Await Task.Delay(500) ' Simulate chunk processing
' Periodically check for cancellation in long-running operations
If token.IsCancellationRequested Then
Console.WriteLine("Cancellation requested. Throwing exception.")
token.ThrowIfCancellationRequested() ' This will trigger an OperationCanceledException
End If
Next i
' Simulate PDF creation after the long process
Dim pdf = Await Renderer.RenderHtmlAsPdfAsync("<h1>Hello, PDF!</h1>")
' Save the PDF after ensuring no cancellation occurred
pdf.SaveAs("output.pdf")
Console.WriteLine("PDF generated successfully.")
Catch e1 As OperationCanceledException
' Handle task cancellation
Console.WriteLine("PDF generation was canceled.")
Catch ex As Exception
' Handle other exceptions
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Function
End Class
Public Class Program
Public Shared Async Function Main(ByVal args() As String) As Task
' Create a CancellationTokenSource
Dim cancellationTokenSource As New CancellationTokenSource()
' Creating our one cancellation token
Dim token = cancellationTokenSource.Token
' Start the PDF generation task
Dim pdfGenerator As New PdfGenerator()
Dim pdfTask As Task = pdfGenerator.GeneratePdfWithCancellation(token)
' Simulate a cancellation scenario
Console.WriteLine("Press any key to cancel PDF generation...")
Console.ReadKey()
' Cancel the task by calling Cancel() on the CancellationTokenSource
cancellationTokenSource.Cancel()
Try
' Await the task to handle any exceptions, such as cancellation
Await pdfTask
Catch e1 As OperationCanceledException
' Confirm the cancellation
Console.WriteLine("The PDF generation was canceled.")
Finally
cancellationTokenSource.Dispose()
End Try
Console.WriteLine("Program finished.")
End Function
End Class
控制台輸出
PDF 输出
在此範例中,我們展示如何在 C# 程式中使用 CancellationToken 來取消使用 IronPDF 的長時間 PDF 生成任務。 代碼分為兩個部分:PDF生成過程(PdfGenerator類)和主程序邏輯(Program類)。
在多種實際情況下,使用一個或多個取消標記(Cancellation Tokens)與IronPDF結合,可以提升應用程式的性能和用戶體驗。 以下是一些範例:
在網絡應用程式中,使用者經常會執行諸如以 PDF 格式生成報告等操作。 但是,如果使用者離開頁面或關閉瀏覽器,系統可以檢測到此情況並使用CancellationToken來停止 PDF 的生成過程。
HttpContext.Response.RegisterForDispose(CancellationTokenSource);
HttpContext.Response.RegisterForDispose(CancellationTokenSource);
HttpContext.Response.RegisterForDispose(CancellationTokenSource)
這個簡單的實現允許網絡伺服器更有效地擴展,不再將資源專用于不再需要的任務。
在報表應用程式中,使用者可能會要求將大型資料集匯出為PDF格式。 如果使用者改變主意或發出不正確的查詢,CancellationToken 允許您在任務中途取消,以防止資源浪費。
在背景服務或微服務中,像生成大型 PDF 批次這樣耗時的任務,可以更有效地使用CancellationToken進行管理。 當服務即將關閉或縮減規模時,正在進行的任務可以被乾淨地取消,確保沒有數據丟失或損壞。
現在,我們已經結束了今天關於在 IronPDF 中使用 cancellationtokens 的討論,您將能夠像專業人士一樣在您的 PDF 專案中實施它們! 使用C# CancellationToken與IronPDF相結合,可以打造更高效、響應更快速的應用程式,以優雅地處理PDF生成任務。 這種方法啟用協作取消模型,允許任務在執行過程中的安全點檢查取消請求,而非被突然終止。
無論您是在管理長時間運行的報告、Web應用中的按需PDF生成,還是後台服務,整合CancellationToken或同時使用多個令牌,確保可以取消不必要的任務,從而防止資源浪費並提升使用者體驗。
只需幾行程式碼,您就可以提升應用程式的擴展性和響應能力,同時讓使用者對其操作有更多掌控。 如果您還沒有探索過IronPDF,現在是嘗試免費試用的最佳時機,並發現其強大的PDF生成功能如何改變您的C#項目。