C# 简单模拟 程序内部 消息订阅发布功能

文章目录

前言

我想做个简单的消息发布订阅功能,但是发现好像没有现成的工具类。要么就是Mqtt这种消息订阅发布。但是我只想程序内部进行消息订阅发布,进行程序的解耦。那没办法了,只能自己上了

模拟消息订阅发布

在Utils 的MessageHelper

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NetCore.Utils
{
    public class MessageHelper
    {
        public static List<Message> Messages = new List<Message>();

        /// <summary>
        /// 消息订阅
        /// </summary>
        public static void Subscribe(string topic,string key, Action<object> action)
        {
            var model = Messages.Where(item => item.Topic == topic && item.Key == key).FirstOrDefault();
            if (model == null)
            {
                model = new Message()
                {
                    Topic = topic,
                    Key = key,

                };

                Messages.Add(model);
            }

            model.Actions += action;

        }

        /// <summary>
        /// 消息推送
        /// </summary>
        public static void Publish(string topic,string key,object value)
        {
            var model = Messages.Where(item => item.Topic == topic && item.Key == key).FirstOrDefault();
            if (model != null)
            {
                model.Actions(value);
            }

        }

    }

    public class Message
    {
        public string Topic { get; set; }

        public string Key { get; set; }

        public Action<object> Actions { get; set; }
    }
}

使用

csharp 复制代码
static void Main(string[] args)
{
     MessageHelper.Subscribe("Topic1", "key1", (res) =>
     {
         var _res = ((string Name, int Age))res;
         Console.WriteLine(_res.ToString());
         Console.WriteLine("我被调用了1");
     });
     MessageHelper.Subscribe("Topic2", "key1", (res) =>
     {
         Console.WriteLine("我被调用了2");

     });
     MessageHelper.Subscribe("Topic3", "key1", (res) =>
     {
         Console.WriteLine("我被调用了3");

     });
     MessageHelper.Subscribe("Topic4", "key1", (res) =>
     {
         Console.WriteLine("我被调用了4");

     });
     MessageHelper.Publish("Topic1","key1",(Name:"嘟嘟",Sex:"12"));
     Console.ReadLine();
 }

注意事项

这里我用了元祖来进行临时变量的传值。元祖如何使用请看我的另一篇文章。元祖用来做临时变量特别好用

C# 元祖,最佳的临时变量。

相关推荐
旖旎夜光2 分钟前
【C++ 基础入门】C++11 新特性(中):右值引用、移动语义与完美转发
开发语言·c++·笔记·学习
Lansonli11 分钟前
大数据Spark(八十八):Spark任务资源之Standalone集群测试
java·服务器·spark
ShineWinsu25 分钟前
对于Qt:QTabWidget常见属性的解析
开发语言·数据库·c++·qt·浏览器·qtabwidget·标签页
budingxiaomoli29 分钟前
Spring AOP
java·spring·java-ee
特立独行的猫A34 分钟前
Ionic + 仓颉语言的 cj-tauri 开发框架实战:开发精美移动端 APP
java·后端·python
nice_lcj5201 小时前
LRU 缓存入门:它是什么、怎么用、面试怎么手写
java·数据结构·缓存·面试·lru
普通人61 小时前
WebGL与WebGPU入门指南
开发语言·webgl·1024程序员节
꧁细听勿语情꧂1 小时前
直接选择排序,堆排序,冒泡排序,递归快速排序、hoare版本、挖坑法、lomuto前后指针,非递归快速排序
c语言·开发语言·数据结构·算法
SomeOtherTime1 小时前
Rust集合(AI回答)
开发语言·后端·rust
文丑颜不良啊2 小时前
LeetCode2741~2760题目解析
java·leetcode