XPS从不同于线程的线程打印Visuals - 是否可能?

时间:2013-07-11 16:37:03

标签: c# .net wpf multithreading xps

为什么我在尝试写入XPS文档时会遇到这个奇怪的异常?

XpsPackagingException: 
Package already has a root DocumentSequence or FixedDocument.

我的目标是将WPF Visual打印到XPS文件中,但由于可视树太大,打印过程可能非常慢,所以我想知道如何在后台线程上打印XPS文件,所以我的用户不会因为申请冻结而烦恼。

这是我的代码:

Dispatcher otherThreadDispatcher;
public MainWindow()
{
    InitializeComponent();
    Thread thread = new Thread(() =>
    {
       otherThreadDispatcher =  Dispatcher.CurrentDispatcher;
       printIt.Click += new RoutedEventHandler(printIt_Click);
       System.Windows.Threading.Dispatcher.Run();
    });
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
}

void printIt_Click(object sender, RoutedEventArgs e)
{
    otherThreadDispatcher.Invoke(new Action(() =>
    {
       using (XpsDocument myDoc = new XpsDocument("foo.xps", FileAccess.ReadWrite))
       {
           XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(myDoc);
           var collator = writer.CreateVisualsCollator();
           collator.BeginBatchWrite();
           collator.Write(someImageToPrint);
           collator.EndBatchWrite();
       }
    }));
}

1 个答案:

答案 0 :(得分:0)

为什么不使用 async await 或Tasks等异步模式?这样你就不用担心线程太多了。