4

在演员模型中,演员有某种消息循环,其中使用例如模式匹配来匹配消息(取决于c语言)

例如伪 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 上调用方法将导致将异步消息发布到仅处理一种消息的消息队列上;一种行为。但是,与消息关联的行为包含在消息本身中(从公共方法发布)

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

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

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

4

2 回答 2

1

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

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

于 2011-05-17T13:15:12.607 回答
0

我会说你的方法是合理的。

实际上,将 F# 代理封装在接口后面是一种很好的做法,它自己会向代理发送消息:

type IPrintText =
    abstract Stop : unit -> unit
    abstract Print : string -> unit

module Printer =
    type private Message =
        | PrintText of string
        | Stop

    let Start () =
        let agent =
            MailboxProcessor.Start (fun inbox ->
                    let rec loop () = async {
                            let! msg = inbox.Receive()

                            return!
                                match msg with
                                | PrintText text ->
                                    printfn "%s" text
                                    loop ()
                                | Stop -> async.Zero()
                        }
                    loop ())

        { new IPrintText with
            member x.Stop () = agent.Post Stop
            member x.Print text = agent.Post <| PrintText text }

let agent = Printer.Start ()

agent.Print "Test"
agent.Stop ()
于 2011-11-18T16:02:45.680 回答