WPF:是否无法在后台线程中加载 UI?
我正在制作一个构建大型 FlowDocument 的应用程序。构建FlowDocument的耗时约为3~4秒。
所以我喜欢在BackgroundWorker中构建FlowDocument,而不是UI线程。但BackgroundWorker无法返回WPF UI对象。 (发生了 InvalidOperationException 异常。)
我该如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果你想在另一个线程中构建 FlowDocument,它必须是第二个 UI 类型线程,而不是 BackgroundWorker。不管文档如何规定,您都可以构建多个 UI 类型线程。但是,您不能在一个线程中创建 UI 对象,然后在另一线程中使用它们。不过,您可以将 FlowDocument 保存到磁盘,然后在前台 UI 线程中重新加载它。
这篇文章有一个很好的例子,有两个UI线程,事实上我已经使用此代码在后台线程中处理 XPS 文件,与您正在做的非常相似。确保您的第二个 UI 线程设置为 STA 单元状态,并且正如我所说,不要尝试在一个线程或另一个线程中使用在一个线程中创建的任何 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.
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.