WEB开发网
开发学院软件开发C语言 适合C# Actor的消息执行方式(2):C# Actor的尴尬... 阅读

适合C# Actor的消息执行方式(2):C# Actor的尴尬

 2010-09-30 20:50:29 来源:WEB开发网   
核心提示: 首先还是定义PingMsg和PongMsg:typePingMsg=|PingofPongMsgActor|FinishedandPongMsg=|PongofPingMsgActor这里体现了F#类型系统中的Discriminated Unions,简单地说,适合C# Actor的消息执行方式

首先还是定义PingMsg和PongMsg:

type PingMsg = 
  | Ping of PongMsg Actor 
  | Finished 
and PongMsg = 
  | Pong of PingMsg Actor

这里体现了F#类型系统中的Discriminated Unions。简单地说,它的作用是把一种类型定义为多种表现形式,这个特性在Haskell等编程语言中非常常见。Discriminated Unions非常适合模式匹配,现在的ping对象和pong对象便可定义如下(在这里还是使用了ActorLite,而不是F#标准库中的MailboxProcessor来实现Actor模型):

let (<<) (a:_ Actor) msg = a.Post msg 
 
let ping = 
  let count = ref 5 
  { new PongMsg Actor() with 
    override self.Receive(message) = 
      match message with 
      | Pong(pong) -> 
        printfn "Ping received pong" 
        count := !count - 1 
        if (!count > 0) then 
          pong << Ping(self) 
        else 
          pong << Finished 
          self.Exit() } 
 
let pong = 
  { new PingMsg Actor() with 
    override self.Receive(message) = 
      match message with 
      | Ping(ping) -> 
        printfn "Pong received ping" 
        ping << Pong(self) 
      | Finished -> 
        printf "Fininshed" 
        self.Exit() }

上一页  1 2 3 4 5 6 7  下一页

Tags:适合 Actor 消息

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接