修复 IronPDF 中的内存泄露
如果您在使用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
在 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能够发展到今天的程度,是因倾听用户的错误报告和功能请求,所以感谢您的支持。

