How to write async background workers that work on WPF flowdocument
I'm trying to write a background worker that processes a flowdocument. I can't access the properties of flowdocument objects because of the thread verification. I tried to serialize the document and loaded it on the worker thread which actually solved the thread verfication issue. However, once the processing is complete I also need to use things like TextPointer objects. Those objects 开发者_开发知识库now point to a objects in the copy not the original.
Can anyone suggest the best way to approach such background processing in WPF?
You can't, WPF objects can only be accessed from the thread that created them so by definition you can't do any background processing on them.
But, as you already discovered you can use serialization techniques to create a copy in another thread and you can serialize the result back.
XamlWriter/XamlReader can serialize almost every WPF object but can be slow on large object graphs.
And for TextPointer maybe you can use GetOffsetToPosition/GetPositionAtOffset to recreate an equivalent TextPointer back in the main thread.
Another options is to use freezables, objects that inherit from Freezeable can be used from other threads (after the Freeze method is called), documents are not freezable but drawing and geometries are - so you may be able to transfer document "fragments" between threads as drawings.
精彩评论