XAML到XPS内存泄漏

时间:2015-06-17 07:16:16

标签: wpf xaml memory-leaks dispatcher xps

对于Windows服务项目,我必须以xps格式制作报告。我有xaml代码,我变成了一个xps文档:

private void th_PrintErrorReport(OrderReportData reportData)
{
  ...

  //Use the XAML reader to create a FlowDocument from the XAML string.
  FlowDocument document = XamlReader.Load(new XmlTextReader(new  StringReader(vRawXaml))) as FlowDocument;

  //create xps file
  using (XpsDocument xpsDoc = new XpsDocument(vFilePath, System.IO.FileAccess.Write, CompressionOption.Maximum))
  {
    // create a serialization manager
    using (XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false))
    {
      // retrieve document paginator
      DocumentPaginator paginator = ((IDocumentPaginatorSource)document).DocumentPaginator;

      // save as XPS
      rsm.SaveAsXaml(paginator);

      rsm.Commit();
    }
  }
}

这可行,但遗憾的是会产生内存泄漏,每个创建的报告都会在内存中保留wpf控件(contentpresent,labels等)。我用内存分析器检查了这个。我查看了this onethis one等主题,这让我觉得wpf调度程序/消息泵是问题所在。为了使消息泵运行,我将代码更改为:

    public void StartHandling()
    {
        _ReportPrintingActive = true;

        //xaml parsing has to run on a STA thread
        _ReportPrintThread = new Thread(th_ErrorReportHandling);
        _ReportPrintThread.SetApartmentState(ApartmentState.STA);
        _ReportPrintThread.Name = "ErrorReportPrinter";
        _ReportPrintThread.Start();
    }

    private void th_ErrorReportHandling()
    {            
        Dispatcher.Run();
    }

    public void PrintErrorReport(OrderReportData reportData)
    {
        Action action = () =>
        {
            th_PrintErrorReport(reportData);
        };
        Dispatcher.FromThread(_ReportPrintThread).BeginInvoke(action);
    }

但仍然没有成功。我错过了什么?

1 个答案:

答案 0 :(得分:0)

使用此帖子中的反射代码使内存泄漏消失:https://stackoverflow.com/a/2410588/687462