如何编写在 WPF flowdocument 上工作的异步后台工作程序
我正在尝试编写一个处理流程文档的后台工作人员。由于线程验证,我无法访问 flowdocument 对象的属性。我尝试序列化文档并将其加载到工作线程上,这实际上解决了线程验证问题。但是,一旦处理完成,我还需要使用 TextPointer 对象之类的东西。这些对象现在指向副本中的对象而不是原始对象。
谁能建议在 WPF 中进行此类后台处理的最佳方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不能,WPF 对象只能从创建它们的线程访问,因此根据定义,您不能对它们进行任何后台处理。
但是,正如您已经发现的那样,您可以使用序列化技术在另一个线程中创建副本,并且可以将结果序列化回来。
XamlWriter/XamlReader 可以序列化几乎每个 WPF 对象,但在大型对象图上可能会很慢。
对于 TextPointer,也许您可以使用 GetOffsetToPosition/GetPositionAtOffset 在主线程中重新创建等效的 TextPointer。
另一个选择是使用 freezables,从 Freezeable 继承的对象可以从其他线程使用(调用 Freeze 方法后),文档不可冻结,但绘图和几何图形可以 - 因此您可以在线程之间传输文档“片段”作为图纸。
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.