C#下一个简单的Actor模型实现
2022/8/12 1:24:07
本文主要是介绍C#下一个简单的Actor模型实现,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
网上关于Actor的内容有很多,这里提供一种简单的实现。直接上码:
1 public abstract class Actor<T> 2 { 3 public static readonly int StateWaiting = 0; 4 public static readonly int StateExecuting = 1; 5 public static readonly int StateExit = 2; 6 7 private readonly Queue<T> _messages; 8 private volatile int _status; 9 10 public bool IsBusy => _status == StateExecuting; 11 12 protected Actor() 13 { 14 _messages = new Queue<T>(); 15 } 16 17 public void Receive(T message) 18 { 19 if (IsValid(message)) 20 { 21 lock (_messages) 22 { 23 _messages.Enqueue(message); 24 } 25 26 StartHandleMessage(); 27 } 28 } 29 30 protected abstract bool IsValid(T message); 31 32 private void StartHandleMessage() 33 { 34 if (Interlocked.CompareExchange(ref _status, StateExecuting, StateWaiting) == StateWaiting) 35 { 36 var msg = _messages.Dequeue(); 37 ThreadPool.QueueUserWorkItem(DoHandleMessage, msg); 38 } 39 } 40 41 private void DoHandleMessage(object message) 42 { 43 if (_status != StateExit) 44 { 45 HandleMessageImpl((T)message); 46 47 if (_messages.Count > 0) 48 { 49 var msg = _messages.Dequeue(); 50 DoHandleMessage(msg); 51 } 52 else 53 { 54 _status = StateWaiting; 55 } 56 } 57 } 58 59 protected abstract void HandleMessageImpl(T message); 60 61 public void Exit() 62 { 63 _status = StateExit; 64 } 65 } 66 }
这篇关于C#下一个简单的Actor模型实现的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-12-06使用Microsoft.Extensions.AI在.NET中生成嵌入向量
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#