XAML to XPS memory leak

662 views Asked by At

For a windows service project i have to make reports in xps format. I have xaml code that i turn into an xps document:

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();
    }
  }
}

This works but unfortunately creates a memory leak, each report created leaves the wpf controls (contentpresent, labels, etc) in memory. I checked this with a memory profiler. I checked topics like this one and this one which made me think that the wpf dispatcher/message pump is the problem. To make the message pump run i changed my code to:

    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);
    }

But still no success. What am i missing ?

1

There are 1 answers

0
svh On BEST ANSWER

Using the reflection code from this post made the memory leak go away : https://stackoverflow.com/a/2410588/687462