修复 IronPDF 中的内存泄露
如果您在使用IronPDF时遇到明显的内存泄漏,我们希望了解这一情况。 我们最资深的工程师将集中力量解决一旦确定的内存泄漏问题。
以下是向support@ironsoftware.com报告内存泄漏的方法:
1. 更新到最新的IronPdf版本
如果您还没有,请更新到最新的IronPdf版本。
2. 请确保已释放您的 IDisposable 对象
绝大多数已报告的内存泄漏都是由于不当使用.NET接口造成的。
如果任何.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
在 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调试器内存分析器可能仍然显示增长。 在使用高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
在此之后,内存使用图表应下降到正常但非零水平。
4. 如果您仍然有内存泄漏 - 请报告
这将被视为极高优先级处理。 请阅读本指南,其中解释了如何找到您的日志文件并报告问题,这样不会需要额外的信息。
这份3分钟的阅读将帮助我们以100%的准确性重现您的问题,确保我们不浪费时间。
谢谢您 - 没有人喜欢内存泄漏,包括我们。 在处理HTML渲染、Interop、图形和流等"低级"或系统对象时,它们有可能发生。 所以,让我们修复它们吧!
IronPDF能够发展到今天的程度,是因倾听用户的错误报告和功能请求,所以感谢您的支持。

