WPF:在后台线程中加载UI是不可能的?

时间:2021-07-23 20:58:34

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

我正在制作一个构建一个巨大的FlowDocument的应用程序。构建FlowDocument所用的时间约为3~4秒。

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

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

how can i solve this problem?

我怎么解决这个问题?

1 个解决方案

#1


7  

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.

如果要在另一个线程中构建FlowDocument,则必须是第二个UI类型的线程,而不是BackgroundWorker。尽管文档说的是,但您可以构建多个UI类型的线程。但是,您无法在一个线程中创建UI对象,而在另一个线程中使用它们。您可以将FlowDocument保存到磁盘,然后在前台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.

本文有两个UI线程的好例子,实际上我已经使用这段代码在后台线程中处理XPS文件,与你正在做的非常相似。确保你的第二个UI线程设置为STA的公寓状态,正如我所说,不要尝试在一个不同的线程中使用在一个线程中创建的任何UI对象。它不会起作用。

#1


7  

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.

如果要在另一个线程中构建FlowDocument,则必须是第二个UI类型的线程,而不是BackgroundWorker。尽管文档说的是,但您可以构建多个UI类型的线程。但是,您无法在一个线程中创建UI对象,而在另一个线程中使用它们。您可以将FlowDocument保存到磁盘,然后在前台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.

本文有两个UI线程的好例子,实际上我已经使用这段代码在后台线程中处理XPS文件,与你正在做的非常相似。确保你的第二个UI线程设置为STA的公寓状态,正如我所说,不要尝试在一个不同的线程中使用在一个线程中创建的任何UI对象。它不会起作用。