標籤:output ring 國外 let linq 實現 account comm logs
最近學了點 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,但是還是很不透徹~
c# 初識Actor Model