在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
在現代軟體開發中,高效管理長時間運行的任務是關鍵,特別是在需要生成大型或複雜 PDF 文件的應用程式中。 C# 開發人員經常依賴 IronPDF 進行無縫的 PDF 創建,但處理可能冗長的 PDF 生成任務需要一種管理用戶中斷或取消的方法。
This is where the取消令牌在 C# 中發揮作用。 通過將其整合與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 套件管理器主控台
To安裝 IronPDF使用 NuGet 套件管理器主控台,開啟 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 就會被添加到您的專案中。
損壞的圖片 從Pixabay添加,從你的文件中選擇或拖放圖片到這裡。
安裝 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 類別)和主要程式邏輯(程式類別).
我們在main方法中使用CancellationTokenSource創建取消令牌來源。(),然後藉由將 CancellationTokenSource** 的 Token 屬性傳遞給它來創建我們的令牌物件。
*ChromePdfRenderer用於從IronPDF庫中將HTML內容渲染成PDF文件。
在多種實際情況下,使用一個或多個取消標記與 IronPDF 結合可以提升您的應用程式效能和使用者體驗。 以下是一些範例:
在網絡應用程式中,使用者經常會執行諸如以 PDF 格式生成報告等操作。 然而,如果用戶離開頁面或關閉瀏覽器,系統可以檢測到這一點並使用CancellationToken來停止PDF生成過程。
HttpContext.Response.RegisterForDispose(CancellationTokenSource);
HttpContext.Response.RegisterForDispose(CancellationTokenSource);
HttpContext.Response.RegisterForDispose(CancellationTokenSource)
這個簡單的實現允許網絡伺服器更有效地擴展,不再將資源專用于不再需要的任務。
在報表應用程式中,使用者可能會要求將大型資料集匯出為PDF格式。 如果使用者改變主意或查詢錯誤,CancellationToken 允許您在中途取消任務,防止資源浪費。
在背景服務或微服務中,像生成大型 PDF 批次這樣耗時的任務可以更有效地使用 CancellationToken 來管理。 當服務即將關閉或縮減規模時,正在進行的任務可以被乾淨地取消,確保沒有數據丟失或損壞。
現在我們已經結束了今天關於在 IronPDF 中使用取消令牌的討論,您將能夠像專業人士一樣將它們應用到您的 PDF 專案中。! 使用 C# CancellationToken 配合IronPDF使您能夠構建更高效、響應更快的應用程式,以優雅地處理 PDF 生成任務。 這種方法啟用協作取消模型,允許任務在執行過程中的安全點檢查取消請求,而非被突然終止。
無論是管理長時間的報告、網路應用程式中的隨需 PDF 生成,還是背景服務,加入 CancellationToken 或同時使用多個 token,都能確保不必要的任務可以被取消,防止資源浪費並提升使用者體驗。
只需幾行程式碼,您就可以提升應用程式的擴展性和響應能力,同時讓使用者對其操作有更多掌控。 如果您還沒有探索過IronPDF,現在是嘗試的最佳時機免費試用並探索其強大的 PDF 生成功能如何改變您的 C# 項目。