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

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

 2010-09-30 20:50:29 来源:WEB开发网   
核心提示: 对于Pong对象来说,如果接受到PingMsg.Ping消息,适合C# Actor的消息执行方式(2):C# Actor的尴尬(4),则回复一个PongMsg.Pong,如果接受的消息为PingMsg.Finished,同样是弱类型,同样得不到静态检查,便立即退出:publicclassPong

对于Pong对象来说,如果接受到PingMsg.Ping消息,则回复一个PongMsg.Pong。如果接受的消息为PingMsg.Finished,便立即退出:

public class Pong : Actor<Message> 
{ 
  protected override void Receive(Message message) 
  { 
    if (message.Tag.Equals(PingMsg.Ping)) 
    { 
      Console.WriteLine("Pong received ping"); 
 
      var ping = message.Arguments[0] as Actor<Message>; 
      ping.Post(new Message(PongMsg.Pong, this)); 
    } 
    else if (message.Tag.Equals(PingMsg.Finished)) 
    { 
      Console.WriteLine("Finished"); 
      this.Exit(); 
    } 
  } 
}

启动乒乓测试:

new Ping(5).Start(new Pong());

结果如下:

Pong received ping 
Ping received pong 
Pong received ping 
Ping received pong 
Pong received ping 
Ping received pong 
Pong received ping 
Ping received pong 
Pong received ping 
Ping received pong 
Finished

从上述代码中可以看出,由于没有Erlang的模式匹配,我们必须使用if…else…的方式来判断消息的Tag,接下来还必须使用麻烦而危险的cast操作来获取参数。更令人尴尬的是,与Erlang相比,在C#中使用Tag Message没有获得任何好处。同样是弱类型,同样得不到静态检查。那么好处在哪里?至少我的确看不出来。

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

Tags:适合 Actor 消息

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