WPF: is it not possible to load the user interface in a background thread?

I am creating an application that will build a huge FlowDocument. The elapsed time to create a FlowDocument was about 3-4 seconds.

So I like to create a FlowDocument in BackgroundWorker, not in a UI thread. but BackgroundWorker cannot return a WPF interface object. (This threw an InvalidOperationException.)

how can i solve this problem?

+6
source share
1 answer

If you want to create a FlowDocument in another thread, it must be the second UI thread, not BackgroundWorker. Despite what the documentation says, you can create more than one user interface thread. However, you cannot create interface objects in one thread and use them in another. You can save the FlowDocument to disk and then reload it in the foreground user interface stream.

This article has a good example with two user interface threads, and I actually used this code to process XPS files in a background thread very similar to what you are doing. Make sure that your second UI thread is set to STA state, and as I said, do not try to use any UI objects created in one thread in another thread. This will not work.

+7
source

Source: https://habr.com/ru/post/894514/


All Articles