【发布时间】:2019-03-03 13:58:49
【问题描述】:
当一切都在同一个线程上时,以下代码可以正常工作。但是,当在后台线程上制作 FixedDocument 时,将 PrintPreview 移动到 UI 线程时,我得到:
"调用线程无法访问该对象,因为不同的 线程拥有它。”
问题线是:
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();
}
}
【问题讨论】:
标签: c# wpf multithreading