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年以后的版本中可能包含非托管对象。

最常见的解决方案

最佳解决方案通常是在引用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
$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. 如果您仍然有内存泄漏 - 请报告

这将被视为极高优先级处理。 请阅读本指南,其中解释了如何找到您的日志文件并报告问题,这样不会需要额外的信息。

这份3分钟的阅读将帮助我们以100%的准确性重现您的问题,确保我们不浪费时间。

工程请求PDF

谢谢您 - 没有人喜欢内存泄漏,包括我们。 在处理HTML渲染、Interop、图形和流等“低级”或系统对象时,它们有可能发生。 所以,让我们修复它们吧!

IronPDF能够发展到今天的程度,是因倾听用户的错误报告和功能请求,所以感谢您的支持。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

准备开始了吗?
Nuget 下载 16,154,058 | 版本: 2025.11 刚刚发布