开发者

How do I create document in the background, print it in a viewer?

I have a function that prints letters. They are created in PDF, then pulled into a PDFViewer and printed.

There is demand for some features with greater control over the printing, so it would be good to do the letters in a background thread so the UI stays active. However 开发者_开发知识库when I try to send the document to the PDFViewer, I get a "cross thread operation" error.

I don't want to be creating a new PDFViewer for each 1-page document. What's the best way to create the letters in the background, and then get them printed?


You need to dispatch the printing to the thread which created the PDFViewer. So if you created the viewer on the UI thread you need to execute the printing in the UI thread once you have finished creating the document:

Application.Current.Dispatcher.BeginInvoke(() => PrintStuff())


The way I usually resolve this is to write a method that messes with the threading issue. I tend to write an extension method:

public static class ControlExtensions
{
    public static void Invoke(this Control control, Action action)            
    {            
        if (control.InvokeRequired)
            control.Invoke(action);
        else
            action();
    }
}

And the usage looks like:

pdfViewer.Invoke(() => pdfViewer.Add(pdfDocument));

Most WinForms application have a notion of a "UI Thread", but there isn't any one single thread that all UI most be done on. What is important is that some operations on controls can only be done on threads that they were created on. Given that, it's safest to ask the control to invoke your action so that it will ensure that the execution is done on the thread it was created on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜