gpt4 book ai didi

c# - 在 BackgroundWorker 线程上创建 FlowDocument

转载 作者:行者123 更新时间:2023-12-05 05:28:28 27 4
gpt4 key购买 nike

我需要从大量数据中动态生成 FlowDocument。因为这个过程需要几分钟,所以我想在后台线程上执行操作而不是让 UI 挂起。

但是,我无法在非 UI 线程上生成 FlowDocument,否则尝试插入矩形和图像会导致运行时错误,提示它不是 STA 线程。

StackOverflow 上有几个线程似乎涉及我遇到的相同问题:

在第一个链接中有人建议如下:

"What I'd do: use a XamlWriter and serialize the FlowDocument into an XDocument. The serialization task involves the Dispatcher, but once it's done, you can run as many wacky parallel analyses of the data as you want and nothing in the UI will affect it. (Also once it's an XDocument you query it with XPath, which is a pretty good hammer, so long as your problems are actually nails.)"

有人可以详细说明作者的意思吗?

最佳答案

对于任何 future 的访客由于这篇文章,我遇到了同样的问题并解决了所有问题 article

最后做的是在后台线程上创建对象

            Thread loadingThread = new Thread(() =>
{
//Load the data
var documant = LoadReport(ReportTypes.LoadOffer, model, pageWidth);

MemoryStream stream = new MemoryStream();
//Write the object in the memory stream
XamlWriter.Save(documant, stream);
//Move to the UI thread
Dispatcher.BeginInvoke(
DispatcherPriority.Normal,
(Action<MemoryStream>)FinishedGenerating,
stream);
});

// set the apartment state
loadingThread.SetApartmentState(ApartmentState.STA);

// make the thread a background thread
loadingThread.IsBackground = true;

// start the thread
loadingThread.Start();

然后将结果作为 xaml 写入内存流,以便我们可以在主线程中读取它

void FinishedGenerating(MemoryStream stream)
{
//Read the data from the memory steam
stream.Seek(0, SeekOrigin.Begin);
FlowDocument result = (FlowDocument)XamlReader.Load(stream);

FlowDocumentScrollViewer = new FlowDocumentScrollViewer
{
Document = result
};
//your code...

希望它能为其他人节省一些时间:)

关于c# - 在 BackgroundWorker 线程上创建 FlowDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10313143/

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