修復 IronPDF 中的記憶體洩漏
若您在 IronPDF 中遇到明顯的記憶體洩漏問題,我們希望您能告知我們。 一旦發現記憶體洩漏,我們最資深的工程師們將立即集結起來,著手開發熱修復程式。
以下是向 回報記憶體洩漏的方法support@ironsoftware.com:/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 年版本中包含非受管物件。
最常見的解決方案
提及 IDisposable 物件時,最佳做法通常是使用 using 語句
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
在 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
3. 收集垃圾
即使系統運作正常,Visual Studio 除錯器的記憶體分析器仍可能持續顯示數值上升。 當使用高記憶體系統時,.NET 執行環境可能會判斷,讓垃圾資料留在記憶體中直到系統記憶體幾乎滿載,甚至使用交換檔來保留,會是更有效率的作法。
在以下情況下,您可以手動指示 .NET 垃圾回收器於應用程式生命週期的安全時點,將未使用的物件進行回收:
- 無法渲染 PDF
- 一個
IDisposable物件已開啟
實現此目標的一種方式是:
System.GC.Co/llect(); // Invokes the garbage collector
System.GC.WaitForPendingFinalizers(); // Waits for the process to complete
System.GC.Co/llect(); // Optional: Runs additional collection to ensure all objects are cleared
System.GC.Co/llect(); // Invokes the garbage collector
System.GC.WaitForPendingFinalizers(); // Waits for the process to complete
System.GC.Co/llect(); // Optional: Runs additional collection to ensure all objects are cleared
Imports System
GC.Collect() ' Invokes the garbage collector
GC.WaitForPendingFinalizers() ' Waits for the process to complete
GC.Collect() ' Optional: Runs additional collection to ensure all objects are cleared
此後,記憶體使用量圖表應回落至正常(但非零)的水平。
4. 若您仍遇到記憶體洩漏問題 - 請回報
此要求將被視為極高優先級事項。 請閱讀本指南,其中說明如何查找您的日誌檔案,並以無需補充說明的方式回報問題。
這篇只需 3 分鐘的閱讀內容,將協助我們 100% 精準地重現您的問題,確保不會浪費您的時間。
感謝您 - 沒有人喜歡記憶體洩漏,我們也不例外。 當處理"低階"或系統物件(如 HTML 渲染、Interop、Graphics 及 Streams)時,這些功能便能實現。 那麼,讓我們來修正它們吧!
IronPDF 之所以能發展至今日的規模,全賴傾聽用戶的錯誤回報與功能需求,在此感謝您的支持。

