对于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 one和this 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);
}
但仍然没有成功。我错过了什么?