在BackgroundWorker线程上创建FlowDocument

问题描述 投票:1回答:2

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

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

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

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

“我要做的是:使用XamlWriter并将FlowDocument序列化为XDocument。序列化任务涉及Dispatcher,但一旦完成,您可以根据需要运行尽可能多的古怪并行数据分析,UI中没有任何内容影响它。(一旦它是一个XDocument你用Qazxswpoi查询它,这是一个非常好的锤子,只要你的问题实际上是钉子。)“

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

c# serialization backgroundworker flowdocument xamlwriter
2个回答
1
投票

对于任何未来的访客,我遇到了同样的问题并解决了所有这一切,感谢这篇文章XPath

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

article

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

            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();

希望它可以节省一些时间:)


0
投票

虽然没有真正详细说明你的引用作者的意思,但也许这可以解决你的问题:如果你把自己挂钩到Application.Idle事件,你可以在那里逐个构建你的FlowDocument。此事件仍然在UI线程中,因此您不会遇到像后台工作者那样的问题。虽然你必须小心不要一次做太多工作,否则你会阻止你的申请。如果可以将生成过程分成小块,则可以在此事件中逐个处理这些块。

© www.soinside.com 2019 - 2024. All rights reserved.