c# - 在 API 中加载 PDF 后释放内存
问题描述
我有一个 ASP .NET Core 3.0 API 应用程序,它返回一个 WPF 页面的 PDF 文件。它自己生成 WPF 页面,然后将其转换为 XPS,这样我就可以将其转换为 PDF,但是当它完成加载 api 时,它不会从内存中释放它,所以它只是建立起来直到它崩溃。每次生成 PDF 但没有真正成功时,我都实施了 GC.collect。
我使用 IDispossable 从 WPF 应用程序生成 PDF 的类
public QueryAndGenerate(int orderNumber, string XPSPath, string PDFPath, bool throwExceptions = true)
{
Helper.Log("QueryAndGenerate start");
this.XPSPath = XPSPath;
this.PDFPath = PDFPath;
List<byte[]> Bytes = new List<byte[]>();
var rows = QueryAndGenerate.GetDataRows(Properties.Resources.joborderQuery, new QueryAndGenerate.MySqlParameter("ORDERNUMBER", orderNumber));
PDFPaths = new List<string>();
Helper.Log(string.Format("rows from query: {0} lenth: {1}", rows, rows.Count));
try
{
foreach (var row in rows)
{
isMultipleGuidenote = true;
QueryAndGenerate queryAndGenerate = new QueryAndGenerate(orderNumber, row.Field<int>("JOBORDERNUMBER"), XPSPath, PDFPath, throwExceptions);
Bytes.Add(File.ReadAllBytes(PDFPath));
Helper.Log("generated file: "+ row);
}
}
catch (Exception e)
{
Helper.Log(e);
}
PdfDocument outputDocument = new PdfDocument();
foreach (byte[] pdfBytes in Bytes)
{
if (pdfBytes.Length != 0)
{
using (MemoryStream stream = new MemoryStream(pdfBytes))
{
PdfDocument inputDocument = PdfReader.Open(stream, PdfDocumentOpenMode.Import);
foreach (PdfPage page in inputDocument.Pages)
{
outputDocument.AddPage(page);
}
}
}
}
outputDocument.Save(this.PDFPath);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
public void Dispose()
{
xpsControls = null;
jobRow = null;
checkRows = null;
warrantyRows = null;
subAssemblyRows = null;
detailRows = null;
detailToolRows = null;
detailItemRows = null;
PDFPaths = null;
cadmanCheck = null;
}
解决方案
推荐阅读
- c# - 在 SQL 数据库中插入动态列
- unity3d - 如何将 2d 动画导出为 png 文件?
- android - Flutter:getApplicationSupportDirectory 作为同步方法
- actions-on-google - 我们可以用超过 8000 个关于 dialogflow 和 amazon alexa 的问题来制作常见问题解答技能吗?
- javascript - 如何阻止调整大小栏如此故障?
- ios - XCode 构建系统:弄乱预处理器定义和包含的头文件?
- android - 错误:未知参数--licenses颤振医生--android-licenses
- javascript - 在javascript函数之后,图像边距没有推到浏览器页面的边缘
- javascript - 是否可以在同一个 Ejs 页面上显示集合(mongoDb)和所有集合中的每个元素?
- python - 为什么 GCC 编译的 Python 库在编译器版本之间兼容,而 MSVC 则不兼容?