郵箱是Actor模型的一個重要組成部分,負責接收發過來的消息,並保存起來,等待Actor處理。郵箱中維護着兩種隊列,一種是存系統消息,另外一個是存用戶消息,系統省是指Started,Stoping,Stoped之類的,用戶固然指咱們自定義的Actor。this
另外,咱們能夠經過實現IMailboxStatistics接口,來獲取郵箱的狀態變動,而且能夠有多個IMailboxStatistics實現。spa
碼友看代碼:代理
1 using Proto; 2 using Proto.Mailbox; 3 using System; 4 using System.Threading.Tasks; 5 6 namespace P005_Mailboxes 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 var props = new Props() 13 // 用道具代理返回一個IActor實例 14 .WithProducer(() => new MyActor()) 15 //默認郵箱使用無界隊列 16 .WithMailbox(() => UnboundedMailbox.Create(new MyMailboxStatistics())) 17 // 默認的 spawner 構造 Actor, Context 和 Process 18 .WithSpawner(Props.DefaultSpawner); 19 20 //從props衍生pid,pid代理一個actor的地址 21 var pid = Actor.Spawn(props); 22 //把Hello對象交給HelloActor處理 23 pid.Tell(new MyEntity 24 { 25 Message = "this is message" 26 }); 27 Console.ReadLine(); 28 } 29 } 30 public class MyActor : IActor 31 { 32 public Task ReceiveAsync(IContext context) 33 { 34 if (context.Message is MyEntity myEntity) 35 { 36 Console.WriteLine(myEntity.Message); 37 } 38 return Actor.Done; 39 } 40 } 41 public class MyEntity 42 { 43 public string Message { get; set; } 44 } 45 public class MyMailboxStatistics : IMailboxStatistics 46 { 47 public void MailboxEmpty() 48 { 49 Console.WriteLine("郵箱MailboxEmpty"); 50 } 51 52 public void MailboxStarted() 53 { 54 Console.WriteLine("郵箱MailboxStarted"); 55 } 56 57 public void MessagePosted(object message) 58 { 59 Console.WriteLine("郵箱MessagePosted:"+message); 60 } 61 62 public void MessageReceived(object message) 63 { 64 Console.WriteLine("郵箱MessageReceived:"+message); 65 } 66 } 67 }
當消息Posted時,Started時,Received時,郵箱爲空時,這些方法會被前後調用,這裏可對消息做處理。code