Accessing a WPF FlowDocument in a BackGround Process

落爺英雄遲暮 提交于 2019-12-06 08:16:50

The primary issue you're facing is that FlowDocument derives from DispatcherObject, and so you have to engage its Dispatcher to access it. Everything you try to do with this thing is going to take the form of putting items in the Dispatcher's work queue and waiting for it to get around to executing them. Which, if the Dispatcher is the one that's handling the UI, is going to result in exactly what you're trying to avoid: while the Dispatcher is executing your work item, all the remaining mouse clicks and keystrokes are piling up in the Dispatcher's work queue, and the UI will be unresponsible.

What you get out of the FlowDocument being a DispatcherObject is that its content can't change while your long-running task is processing it. Those mouse clicks and keystrokes in the queue may change it once your task is done, but while it's running, they're just accumulating. This is actually kind of important; if you were able to get around using the Dispatcher, you'd face the scenario where something in the UI changed the FlowDocument while your task was running. Then you would have what are commonly known as "problems."

Even if you could clone the FlowDocument and disconnect the clone from the UI's dispatcher, it would still be a DispatcherObject, and you'd still run into the same problem trying to execute multiple tasks on it simultaneously; you'd have the options of serializing your access to it or watching your background thread crash.

To get around this, what you need to do is make some kind of non-DispatcherObject frozen snapshot of the FlowDocument. Then run your task on the snapshot. That way, if the UI, being live, changes the FlowDocument while your task is running, it won't mess up your game.

What I'd do: use a XamlWriter and serialize the FlowDocument into an XDocument. The serialization task involves the Dispatcher, but once it's done, you can run as many wacky parallel analyses of the data as you want and nothing in the UI will affect it. (Also once it's an XDocument you query it with XPath, which is a pretty good hammer, so long as your problems are actually nails.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!