您的位置:首页 > 编程语言 > C#

《通过C#学Proto.Actor模型》之Mailbox

2018-08-30 08:35 363 查看

邮箱是Actor模型的一个重要组成部分,负责接收发过来的消息,并保存起来,等待Actor处理。邮箱中维护着两种队列,一种是存系统消息,另一个是存用户消息,系统省是指Started,Stoping,Stoped之类的,用户当然指我们自定义的Actor。

另外,我们可以通过实现IMailboxStatistics接口,来获取邮箱的状态变更,并且可以有多个IMailboxStatistics实现。

 

码友看代码:

using Proto;
using Proto.Mailbox;
using System;
using System.Threading.Tasks;

namespace P005_Mailboxes
{
class Program
{
static void Main(string[] args)
{
var props = new Props()
// 用道具代理返回一个IActor实例
.WithProducer(() => new MyActor())
//默认邮箱使用无界队列
.WithMailbox(() => UnboundedMailbox.Create(new MyMailboxStatistics()))
// 默认的 spawner 构造  Actor, Context 和 Process
.WithSpawner(Props.DefaultSpawner);

//从props衍生pid,pid代理一个actor的地址
var pid = Actor.Spawn(props);
//把Hello对象交给HelloActor处理
pid.Tell(new MyEntity
{
Message = "this is message"
});
Console.ReadLine();
}
}
public class MyActor : IActor
{
public Task ReceiveAsync(IContext context)
{
if (context.Message is MyEntity myEntity)
{
Console.WriteLine(myEntity.Message);
}
return Actor.Done;
}
}
public class MyEntity
{
public string Message { get; set; }
}
public class MyMailboxStatistics : IMailboxStatistics
{
public void MailboxEmpty()
{
Console.WriteLine("邮箱MailboxEmpty");
}

public void MailboxStarted()
{
Console.WriteLine("邮箱MailboxStarted");
}

public void MessagePosted(object message)
{
Console.WriteLine("邮箱MessagePosted:"+message);
}

public void MessageReceived(object message)
{
Console.WriteLine("邮箱MessageReceived:"+message);
}
}
}

当消息Posted时,Started时,Received时,邮箱为空时,这些方法会被先后调用,这里可对消息作处理。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: