WPF:是否可以在后台线程中加载UI? [英] WPF : Is it impossible to UI load in background thread?

查看:237
本文介绍了WPF:是否可以在后台线程中加载UI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一些应用程序,该应用程序构建了一个大型的FlowDocument.构建FlowDocument所需的时间约为3-4秒.

I've making a some application which build a huge-sized FlowDocument. The elapsed time of building FlowDocument was about 3~4 seconds.

所以我喜欢在BackgroundWorker中构建FlowDocument,而不是UI线程.但是BackgroundWorker无法返回WPF UI对象. (它发生了InvalidOperationException异常.)

So I like to building FlowDocument in BackgroundWorker, not UI thread. but BackgroundWorker can't return WPF UI object. (It occured InvalidOperationException exception.)

我该如何解决这个问题?

how can i solve this problem?

推荐答案

如果要在另一个线程中构建FlowDocument,它必须是第二个UI类型的线程,而不是BackgroundWorker.尽管文档说了什么,您仍然可以构建多个UI类型的线程.但是,您不能在一个线程中创建UI对象,而在另一个线程中使用它们.您可以将FlowDocument保存到磁盘,然后将其重新加载到前景UI线程中.

If you want to build a FlowDocument in another thread, it has to be a second UI-type thread, not a BackgroundWorker. In spite of what the documentation says, you CAN build more than one UI-type thread. However, you cannot create UI objects in one thread, and use them in another. You could save your FlowDocument to disk and then reload it in the foreground UI thread, though.

本文有一个很好的例子有两个UI线程,实际上我已经使用此代码在后台线程中处理XPS文件,这与您正在执行的操作非常相似.确保您的第二个UI线程设置为STA公寓状态,并且正如我所说,请勿尝试使用在一个线程中,在另一个线程中创建的任何UI对象.这行不通.

This article has a good example with two UI threads, and in fact I have used this code to process XPS files in a background thread, very similar to what you are doing. Make sure your second UI thread is set to STA apartment state, and as I said, do not try to use any UI objects created in one thread, in a different thread. It won't work.

这篇关于WPF:是否可以在后台线程中加载UI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆