f# - 在 C# 5/Async CTP 中实现 Actor 模型

标签 f# actor agent async-ctp

在 Actor 模型中, Actor 有某种消息循环,其中消息使用例如匹配。模式匹配(取决于语言 ofc)

例如伪 F#

 let message_loop() = 
     let! message = receive_message() //sync receive message
     match message with
     | Foo(a,b) -> DoStuff(a,b)
     | Bar(c) -> DoOtherStuff(c)
     | _ -> error ("unknown message")
     message_loop()

基本上,消息签名匹配并与要对消息内容执行的某些操作相关联。

这和调用实际方法之间有什么概念上的区别吗?
例如如果我要在 C# 5 中执行以下操作:
class MyActor 
{
   //message signature Foo(a,b)
   public void Foo(int a,string b)
   {
      Act( () => DoStuff(a,b) );
   }

   //message signature Bar(c)
   public void Bar(int c)
   {
      Act( () => DoOtherStuff(c));
   }

   // the rest is infrasturcture code, can be refactored into an Actor Base class


   //this emulates the sync behavior of the above actor
   //each action is pushed onto a queue 
   //and then processed synchronously by the message handler
   private void Act(Action action)
   {
       actions.Post(action); 
   }

   private BufferBlock<Action> actions = new BufferBlock<Action>();

   //this needs max degreee of parallellism = 1 
   private ActionBlock<Action> messageHandler = new ....
}

这样,在 MyActor 上调用方法将导致将异步消息发布到仅处理一种消息的消息队列上;一种行为。
但是,与消息关联的行为包含在消息本身中(从公共(public)方法发布)

那么这是否被认为是在 C# 5/Async CTP 中执行 Actor 的一种干净的方式?

好处是消息被简单地定义为普通消息,而不是像类一样创建笨拙的消息 DTO。

那么这足以让它发挥作用吗?

最佳答案

基于任务的异步和 MailboxProcessor 之间存在细微差别。邮箱处理器将始终在同一个线程中结束,类似于 Winforms 消息循环。任务保持一个 SynchronizationContext。这意味着 Winforms 和 WPF 的行为相同,但在使用线程池时您可能会使用不同的线程。

否则,从概念上讲,对我来说是正确的。

关于f# - 在 C# 5/Async CTP 中实现 Actor 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5776916/

相关文章:

f# - 函数类型的变体 wrt。接口(interface)

java - 使用代理的性能影响

multithreading - F# MailboxProcessor 限制并行度

clojure - var 或 ref/atom/agent 用于常量值?

F#:对复杂列表进行分组

interface - 如何在 F# 中实现返回 void 的接口(interface)成员

syntax - 为什么将表达式的第一行与 let 放在同一行无法编译?

scala - 从 Supervisor 重新启动后向 actor 发送消息

scala - 使 Scala Remote Actors 更加稳定

scala - Akka 2 中调度程序的区别和使用模式有哪些?