我需要将数千个不同格式的 ms office 文档转换为一种通用格式。为了加快速度,我会使用 akka.net 将其并行化。 WordSaveAsActor 应该:
- 在单线程单元中运行
- 持有 Word 应用程序实例
- 在此实例上进行 COM 调用,例如使用从多个并行线程接收到的消息的路径进行 SaveAs(..)
- 任何崩溃都会自行重启
是否可以在 STA 中运行 akka.net actor?如果我以这种方式使用 akka.net,会有任何顾虑吗?
最佳答案
简短的回答是“是的,你可以用 Akka.NET 做到这一点”
正如汉斯在他的评论中指出的那样:
Word doesn't care much about your library. Its interop interface is single-threaded, any call you make from a worker thread is automatically marshaled to the thread that owns the Application object.
您可以使用 Akka.NET 中的调度程序对 actor 的并发需求进行一些控制 - 您可以 read about different types of Akka.NET dispatchers and how they work in our Akka.NET Bootcamp Lesson 2.1 .
对于您的情况,我建议您执行以下操作:
- 在 STA 线程上创建您的
WordSaveAsActor
并将其配置为使用 Akka.NET 中的CurrentSynchronizationContextDispatcher
,您可以通过配置完成此操作:
var wordActor = MyActorSystem.ActorOf(Props.Create(() => new WordSaveAsActor(...)).WithDispatcher("akka.actor.synchronized-dispatcher"))
此 actor 处理的所有消息都将在 STA 线程上自动完成。我们在其他 STA 环境(例如 Windows 窗体 UI)中使用此技术,它大大简化了一切。
- 在使用默认调度程序(CLR 线程池)的其他参与者上执行不需要 Word 的 COM 组件的所有其他工作。这可能包括任何文件复制、打开、移动等。当您需要发送数据时到 word 或从 word 接收数据,您可以让这些 actor 将消息传递给您的
WordSaveAsActor
。
正如 Hans 指出的那样,除非您并行运行 Word 的多个实例,否则您实际上无法利用其 COM API 一次执行多个操作。因此,为了利用 Akka.NET 的并行性,您需要找到一种方法来使用多个参与者来并行化不需要 Word 的操作部分。
关于c# - STA 中的 Akka.net 参与者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28940122/