首页 > 解决方案 > 在 API 中加载 PDF 后释放内存

问题描述

我有一个 ASP .NET Core 3.0 API 应用程序,它返回一个 WPF 页面的 PDF 文件。它自己生成 WPF 页面,然后将其转换为 XPS,这样我就可以将其转换为 PDF,但是当它完成加载 api 时,它不会从内存中释放它,所以它只是建立起来直到它崩溃。每次生成 PDF 但没有真正成功时,我都实施了 GC.collect。

加载几个 PDF 文件后的内存使用情况

我使用 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#wpfasp.net-corememory-leaks

解决方案


推荐阅读