Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF : Is it impossible to UI load in background thread?

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

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?

like image 773
mjk6026 Avatar asked Aug 08 '11 04:08

mjk6026


People also ask

What is UI thread in C#?

A UI thread creates UI elements and waits and responds to events like mouse clicks and key presses. You can only access the UI elements from the UI thread. There are two types of threads: background and foreground. A UI thread is an example of a foreground thread.

What is UI thread in WPF?

The UI thread queues work items inside an object called a Dispatcher. The Dispatcher selects work items on a priority basis and runs each one to completion. Every UI thread must have at least one Dispatcher, and each Dispatcher can execute work items in exactly one thread.

Is WPF multi threaded?

WPF supports a single-threaded apartment model that has the following rules: One thread runs in the entire application and owns all the WPF objects. WPF elements have thread affinity, in other words other threads can't interact with each other.


1 Answers

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.

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.

like image 107
Ed Bayiates Avatar answered Oct 15 '22 06:10

Ed Bayiates