本文看了博客C# 实现 Actor并发模型 (案例版)_51CTO博客_actor并发模型,这里作为条记用,该博客内容写的很具体,这里根本上没有改动。
起首,本文的目次如下:
每个cs文件的代码都有具体的注释,具体代码如下:
1. IActor.cs代码:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApp3.core
- {
- /// <summary>
- /// 无锁并行编程模型(暂时用来处理串行任务,任务串行执行)
- /// </summary>
- public interface IActor
- {
- bool AddMsg(object message); //增加消息
- Task Start(); // 启动服务
- bool Stop(int WaitingTimeout); // 停止服务运行,等待毫秒数
- }
- }
复制代码 2. Actor.cs代码
3.WriteActor.cs代码
- using ConsoleApp3.core;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApp3
- {
- public class WriteActor: Actor
- {
- public WriteActor() : base(nameof(WriteActor)) { }
- 处理信息
- public override Task ProcessAsync(object msg)
- {
- try { Console.WriteLine($"输出 {this.Name} :{msg}");}
- catch(Exception e) { Console.WriteLine($"业务处理异常:{e.Message}"); }
- return Task.CompletedTask;
- }
- }
- }
复制代码 4.AccumulationActor.cs代码
- using ConsoleApp3.core;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApp3
- {
- public class AccumulationActor : Actor
- {
- private int Count = 0;
- private IActor actor;
- public AccumulationActor(IActor actor) : base(nameof(AccumulationActor))
- {
- Count = 0;
- this.actor = actor;
- //Console.WriteLine(nameof(AccumulationActor)); // 输出基类名称
- }
- // 处理信息
- public override Task ProcessAsync(object msg)
- {
- try
- {
- var msgNumber = (int)(msg);
- Count += msgNumber;
- Console.WriteLine($"处理{this.Name} :{msg} ,累积总数:{Count}");
- if (Count >= 100)
- {
- this.actor.AddMsg(Count);
- Count = 0;
- }
- }
- catch(Exception e) { Console.WriteLine($"业务处理异常:{e.Message}"); }
- return Task.CompletedTask;
- }
- }
- }
复制代码 5.program.cs代码
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace ConsoleApp3
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.Title = "Actor Demo of wang";
- //实现一个加法逻辑
- //a累加到100,就发送消息到 b里,让b 输出
- var write = new WriteActor();
- var User = new AccumulationActor(write);
- for (int i = 0; i < 20; i++) { User.AddMsg(i * 30); }
- Thread.Sleep(2000);
- write.Stop();
- User.Stop();
- //释放资源
- Console.WriteLine("示例完毕!");
- Console.ReadLine();
- }
- }
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |