修复 IronPDF 中的内存泄露
如果您在使用IronPDF时遇到明显的内存泄漏,我们希望了解这一情况。 我们最资深的工程师将集中力量解决一旦确定的内存泄漏问题。
以下是向support@ironsoftware.com报告内存泄漏的方法:
1. 更新至最新的IronPDF版本
如果您尚未如此,请更新至最新的IronPDF版本。
2. 确保您已处理完您的IDisposable对象
.NET IDisposable接口的不当使用是导致内存泄漏的主要原因。
如果任何.NET类有一个IDisposable,开发者需要通知它何时使用完成。
有一个常见的误解,认为C#是一种"托管"语言,不需要开发人员负责管理内存。 与这种观点相反,实际上有许多常见的.NET对象开发人员未能释放。
未能手动处理每个IDisposable类实例可能会导致代码中的内存泄漏。
- System.IO.Stream - 由
PdfDocument.Stream属性返回。 - System.Drawing.Image / System.Drawing.Bitmap - 由
PdfDocument.PageToBitmap方法返回。 - IronPdf.PdfDocument - 自身也标记为
IDisposable,因为它可能包含在我们2021-2024年发布的版本中的非托管对象。
最常见的解决方案
最佳解决方案通常是在引用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调试器内存分析器可能仍然显示增长。 在使用高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能够发展到今天的程度,是因倾听用户的错误报告和功能请求,所以感谢您的支持。

