打印流文档时出现问题:“调用线程无法访问此对象,因为不同的线程拥有它”

时间:2016-11-25 14:19:39

标签: wpf multithreading printing backgroundworker

下面的代码一直给我以下错误:调用线程无法访问此对象,因为不同的线程拥有它

我尝试使用:

  • 的SynchronizationContext
  • Application.Current.Dispatcher
  • Windows.Threading.Dispatcher
private void PrintDocument()
    {
        PrintQueue printQueue = null;
        using (var worker = new BackgroundWorker())
        {
            worker.WorkerSupportsCancellation = true;
            try
            {
                worker.DoWork += (s, e) =>
                {
                    string actualServerHostName = "\\\\" + Dns.GetHostEntry(Config.Default.printer.printServer.TrimStart('\\')).HostName;
                    var printServer = new PrintServer(actualServerHostName);
                    printQueue = printServer.GetPrintQueue(Config.Default.printer.defaultPrinterName);
                    printQueue.UserPrintTicket = printDlg.PrintTicket;
                    e.Result = printQueue;
                };
                worker.RunWorkerCompleted += (s, e) =>
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        printQueue = e.Result as PrintQueue;
                        var flowDocument = CreateFlowDocument();
                        PrintFlowDocument(printQueue, flowDocument.DocumentPaginator);
                    }, DispatcherPriority.Send);

                    InProgress = false;
                };
                InProgress = true;
                worker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                worker.CancelAsync();
                throw ex;
            }
        }
    }

private XpsDocumentWriter GetPrintXpsDocumentWriter(PrintQueue printQueue)
    {
        XpsDocumentWriter xpsWriter = PrintQueue.CreateXpsDocumentWriter(printQueue);
        return xpsWriter;
    }

    public void PrintFlowDocument(PrintQueue printQueue, DocumentPaginator document)
    {
        XpsDocumentWriter xpsDocumentWriter = GetPrintXpsDocumentWriter(printQueue);
        PrintDocumentPaginator(xpsDocumentWriter, document);
    }

    private void PrintDocumentPaginator(XpsDocumentWriter xpsDocumentWriter, DocumentPaginator document)
    {
        try
        {
            xpsDocumentWriter.WriteAsync(document);
        }
        catch (Exception ex)
        {
            _dialogService.ShowErrorAsync("Error occured: ", ex.Message);
        }
    }

    private IDocumentPaginatorSource CreateFlowDocument()
    {
        FlowDocument doc = (FlowDocument)Application.LoadComponent(new Uri(@"/[assembly];component/Controls/PrintTicketControl.xaml", UriKind.RelativeOrAbsolute));
        doc.DataContext = this;
        return doc;
    }

PrintDocumentPaginator 方法中调用 xpsDocumentWriter.WriteAsync(document); 时失败。 看看堆栈跟踪,看起来PrintQueue正在爆炸。 我还检查了创建控件的线程,并在调用PrintDocument函数时成功返回主线程。

有什么想法吗? 感谢

0 个答案:

没有答案