【问题标题】:XAML to XPS memory leakXAML 到 XPS 内存泄漏
【发布时间】:2015-09-02 06:47:24
【问题描述】:

对于 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、标签等)留在内存中。我用内存分析器检查了这个。我检查了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);
    }

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

【问题讨论】:

    标签: wpf xaml memory-leaks dispatcher xps


    【解决方案1】:

    使用这篇文章中的反射代码消除了内存泄漏:https://stackoverflow.com/a/2410588/687462

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 1970-01-01
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      • 2012-07-16
      • 2018-04-07
      相关资源
      最近更新 更多