[英]Creating a WinForm on the main thread using a backgroundworker
[英]Creating FlowDocument on BackgroundWorker thread
我需要从大量数据中动态生成FlowDocument
。 因为该过程需要几分钟,所以我想在后台线程上执行该操作,而不要挂起UI。
但是,我无法在非UI线程上生成FlowDocument
,否则尝试插入矩形和图像会导致运行时错误,抱怨它不是STA线程。
StackOverflow上有几个线程似乎都涉及到我遇到的相同问题:
在第一个链接中,有人提出以下建议:
“我要做的是:使用
XamlWriter
并将FlowDocument
序列化为XDocument
。序列化任务涉及Dispatcher
,但是一旦完成,您就可以对数据进行任意古怪的并行分析,而UI中将没有任何东西影响它。(一旦它是XDocument
,只要您的问题实际上是钉子,您就可以使用XPath
查询它,这是一个很好的锤子。)”
有人可以详细说明作者的意思吗?
对于任何未来的访客我面临同样的问题,解决了所有感谢这篇文章文章
最终要做的是在后台线程上创建对象
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...
希望它可以节省一些时间:)
尽管还不确定要详细解释报价作者的意思,但这也许可以解决您的问题:如果您将自己吸引到Application.Idle事件中,则可以在其中逐个构建FlowDocument。 此事件仍在UI线程中,因此您不会像后台工作人员那样遇到问题。 而且,您必须小心不要一次做太多工作,否则将阻止您的应用程序。 如果可以将生成过程分成小块,则在这种情况下,可以逐个处理这些块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.