6

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?

mjk6026
  • 1,484
  • 3
  • 20
  • 38
  • Seriously, a little code could do wonders. Also, Read about background workers,here: http://elegantcode.com/2009/07/03/wpf-multithreading-using-the-backgroundworker-and-reporting-the-progress-to-the-ui/ – loxxy Aug 08 '11 at 04:36

1 Answers1

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.

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.

Ed Bayiates
  • 11,060
  • 4
  • 43
  • 62
  • Oh god. It sounds like I need to build a serialized file of the Flowdocument, or printing to XPS and reload that. thanks. – mjk6026 Aug 08 '11 at 04:46
  • 2
    Basically, yes, unfortunately. But this is much times better than having an unresponsive app for 3-4 seconds. The only other thing you can do is periodically calling a version of DoEvents, though that's not so good, but might be good enough. – Ed Bayiates Aug 08 '11 at 05:49