gpt4 book ai didi

c# - 如何从后台线程使用 FixedDocument?

转载 作者:行者123 更新时间:2023-11-30 12:40:39 26 4
gpt4 key购买 nike

当一切都在同一个线程上时,以下代码可以正常工作。但是,当在后台线程上创建 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();
}
}

最佳答案

这显然是您方法中的 static 修饰符。将其更改为实例方法可以让您方便 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, 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);
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();
}
}
}

关于c# - 如何从后台线程使用 FixedDocument?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41030647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com