当所有内容都在同一个线程上时,以下代码可以正常工作.但是,在后台线程上创建FixedDocument时,将PrintPreview移动到UI线程,我得到:
“The calling thread cannot access this object because a different
thread owns it.”
问题在于:
writer.Write(fixeddocument.DocumentPaginator);
我无法获得dispatcher.invoke / begininvoke – 或其他任何东西来解决这个问题.
那么如何将另一个线程的FixedDocument带到UI线程呢?
(请注意,FixedDocument需要几分钟才能生成,因此必须在后台线程上创建.是的,我已经Google搜索了几个小时而没有找到任何解决方案.如果有,我错过了它).
我一直认为我必须将PrintPreview保持在与FixedDocument相同的线程中 – 我希望不会.
// Print Preview public static void PrintPreview(FixedDocument fixeddocument,CancellationToken ct) { // Was cancellation already requested? if (ct.IsCancellationRequested) ct.ThrowIfCancellationRequested(); MemoryStream ms = new MemoryStream(); using (Package p = Package.Open(ms,FileMode.Create,FileAccess.ReadWrite)) { Uri u = new Uri("pack://TemporaryPackageUri.xps"); PackageStore.AddPackage(u,p); XpsDocument doc = new XpsDocument(p,Compressionoption.Maximum,u.AbsoluteUri); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc); writer.Write(fixeddocument.DocumentPaginator); FixedDocumentSequence fixedDocumentSequence = doc.GetFixedDocumentSequence(); var previewWindow = new PrintPreview(fixedDocumentSequence); Action closeAction = () => previewWindow.Close(); ct.Register(() => previewWindow.dispatcher.Invoke(closeAction) ); previewWindow.ShowDialog(); PackageStore.RemovePackage(u); doc.Close(); } }
解决方法
它显然是你方法中的静态修饰符.将其更改为实例方法可以促进dispatcher:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } // Print Preview public void PrintPreview(FixedDocument fixeddocument,CancellationToken ct) { // Was cancellation already requested? if (ct.IsCancellationRequested) ct.ThrowIfCancellationRequested(); MemoryStream ms = new MemoryStream(); using (Package p = Package.Open(ms,FileAccess.ReadWrite)) { Uri u = new Uri("pack://TemporaryPackageUri.xps"); PackageStore.AddPackage(u,p); XpsDocument doc = new XpsDocument(p,u.AbsoluteUri); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc); //writer.Write(fixeddocument.DocumentPaginator); dispatcher.Invoke(new Action<DocumentPaginator>(writer.Write),fixeddocument.DocumentPaginator); FixedDocumentSequence fixedDocumentSequence = doc.GetFixedDocumentSequence(); var previewWindow = new PrintPreview(fixedDocumentSequence); Action closeAction = () => previewWindow.Close(); ct.Register(() => previewWindow.dispatcher.Invoke(closeAction) ); previewWindow.ShowDialog(); PackageStore.RemovePackage(u); doc.Close(); } } }