I'm trying to write a service that act as a print spooler : it waits for documents to print and print the on the right printer with the right settings (stored in a PrintTicket).
Each time a bunch of document is coming a thread is created for each setting and the documents are printed in parallel in their thread.
It works when I use a WPF application, but when I use the same code in a windows service I get this error on the PrintDialog.PrintVisual function call :
the calling thread cannot access this object because a different thread owns it
When googling for this error I often end up with this thread safe print dialog, but it doesn't provide the PrintVisual function.
Any other idea on how to get rid of this error ?
Thanks for your help
The problem is that the document, or visual, that you're trying to print is currently displayed on the UI thread. In order to get around that, you'll need to recreate the visual. This means that you need something like a copy constructor. What this means is that you need to do
ControlX doc = new ControlX(visualToPrint)
which will create a new reference to the control on non-UI thread. From that point on, since the thread created its own copy of the control, it can now change it and print it how it wants.Remember, after you successfully recreate the control you'll need to force a new layout pass since you're not calling
.Show()
. Do that by calling:.Measure(Rect);
.Arrange(Point, Rect);
.UpdateLayout();