最近學了點 c# dataflow的一些東西,然后國外有個人,用dataflow來實現了,一個Actor模型;
這里做個比較,算是初識我們的actor模型,然后我們再進一步的深入了解一哈;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; namespace Actor_Model { //actor model 的基本使用和示例; //https://blog.jayway.com/2013/11/15/an-actor-model-implementation-in-c-using-tpl-dataflow/#comment-463337 public abstract class Message { } //把所有的action 都通過meg的 形式表達出來; //吧我們的每一動作都看成了信息;讓后將信息傳遞出去,真正的執行,交給我們的具體的actor去執行滴呀; public class Deposit : Message { public decimal Amount { get; set; } } //To check the balance we send a QueryBalance message public class QueryBalance : Message { //The result of the query should be sent as a message to another actor //也就是說查詢出來的信息又交給了另外一個actor 處理了滴呀;信息之間的傳遞; public Actor Receiver { get; set; } } //The final message is the result of the balance chec public class Balance : Message { public decimal Amount { get; set; } } public abstract class Actor { private readonly ActionBlock<Message> _action; public Actor() { _action = new ActionBlock<Message>((msg => { dynamic self = this; dynamic mess = msg; self.Handle(mess); })); } public void Send(Message msg) { _action.Post(msg); } public Task Completion { get { _action.Complete(); return _action.Completion; } } } //Each account has a balance. We want to be able to deposit money and check the balance //實際動作的執行者; public class AccountActor : Actor { private decimal _balance; //存錢 public void Handle(Deposit msg) { _balance += msg.Amount; //deposite money } //查詢余額 public void Handle(QueryBalance msg) { //查詢出來的余額,叫給我們的額新actor去處理; //相當於創建一個新的acto msg.Receiver.Send(new Balance { Amount = _balance }); } } //We also need an actor that outputs the result of the balance query public class OutputActor : Actor { public void Handle(Balance msg) { Console.WriteLine("Balance is {0}", msg.Amount); } } class Program { static void Main(string[] args) { var account = new AccountActor(); var output = new OutputActor(); account.Send(new Deposit { Amount = 50 }); account.Send(new QueryBalance { Receiver = output }); account.Completion.Wait(); output.Completion.Wait(); Console.WriteLine("Done!"); Console.ReadLine(); } } }
看完基本了解actor,但是還是很不透徹~