Fixing Memory Leaks in IronPDF

This article was translated from English: Does it need improvement?
Translated
View the article in English

如果您在使用 IronPDF 時遇到明顯的記憶體洩漏,我們希望了解此情況。 我們最資深的工程師會全力投入研究記憶體洩漏,一旦確定問題後,會即時修復。

以下是向 support@ironsoftware.com 報告記憶體洩漏的方法:

1. 更新至最新版本的 IronPdf

如果您還不是,請更新至最新的 IronPdf 版本。

2. 確保已釋放 IDisposable 物件

大部分報告的記憶體洩漏是由於不正確使用 .NET IDisposable 介面所引起的。

如果任何 .NET 類別有 Dispose() 方法 - 它可能是 IDisposable 並且需要開發者告知程式何時不再使用它。

普遍存在的誤解是 C# 是一種“受管理”的語言,不需要開發者負責管理記憶體。 與此信念相反,實際上存在許多開發者未能釋放的常見 .NET 物件。

未能手動釋放每個 IDisposable 類別實例可能會導致您的程式中出現記憶體洩漏。

  • System.IO.Stream - 由 PdfDocument.Stream 屬性返回。
  • System.Drawing.Image / System.Drawing.Bitmap - 由 PdfDocument.PageToBitmap 方法返回。
  • IronPdf.PdfDocument - 它本身也標記為 IDisposable,因為在我們 2021 - 2024 年的更新中,它可能包含未受管理的物件。

最常見的解決方案

最佳解決方案通常是使用 using 語句來引用 IDisposable 物件。

using(var stream = myPdfDocument.Stream) {
    // Perform operations with the stream here
}
using(var stream = myPdfDocument.Stream) {
    // Perform operations with the stream here
}
Using stream = myPdfDocument.Stream
	' Perform operations with the stream here
End Using
$vbLabelText   $csharpLabel

在 C# 8 中,甚至還有不帶 {} 圍域的 簡捷 版本。

using var stream = myPdfDocument.Stream;
// Perform operations with the stream here
using var stream = myPdfDocument.Stream;
// Perform operations with the stream here
Dim stream = myPdfDocument.Stream
' Perform operations with the stream here
$vbLabelText   $csharpLabel

3. 收集垃圾

即使沒有問題,Visual Studio 的偵錯器內存剖析器也可能繼續顯示增加。 當使用高 RAM 系統時,.NET 執行環境可能認為允許垃圾駐留在記憶體中直到系統 RAM 幾乎滿或甚至使用交換文件更為高效。

可以在應用程式生命週期中安全點告知 .NET 垃圾收集器釋放其未使用的物件,當:

  • 未渲染 PDF
  • 開啟 IDisposable 物件時

完成此操作的一種方法是:

System.GC.Collect(); // Invokes the garbage collector
System.GC.WaitForPendingFinalizers(); // Waits for the process to complete
System.GC.Collect(); // Optional: Runs additional collection to ensure all objects are cleared
System.GC.Collect(); // Invokes the garbage collector
System.GC.WaitForPendingFinalizers(); // Waits for the process to complete
System.GC.Collect(); // Optional: Runs additional collection to ensure all objects are cleared
System.GC.Collect() ' Invokes the garbage collector
System.GC.WaitForPendingFinalizers() ' Waits for the process to complete
System.GC.Collect() ' Optional: Runs additional collection to ensure all objects are cleared
$vbLabelText   $csharpLabel

之後,內存使用圖表應該下降到正常但非零的水平。

4. 如果您仍然有記憶體洩漏 - 請報告

這將被視為極高優先級。 請閱讀這份指南,它說明了如何找到您的日誌文件並報告您的問題,這樣就不需要進一步的信息。

這篇三分鐘的文章將幫助我們以 100% 的準確性重現您的問題,確保不浪費您的時間。

工程請求 PDF

謝謝 - 沒有人喜歡記憶體洩漏,包括我們。 當處理“底層”或系統物件,如 HTML 渲染、Interop、圖形和流等,它們的出現會有可能。 那麼讓我們一起修復它們吧!

IronPDF 只有從聆聽我們用戶的錯誤報告和功能請求中成為今天的樣子,感謝您的支持。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 16,154,058 | 版本: 2025.11 剛剛發布