陈程的技术博客

  • 关于作者
全栈软件工程师
一个专注于技术研究创新的程序员
  1. 首页
  2. 未分类
  3. 正文

用C#封装一个线程安全的缓存器,达到目标定时定量更新入库

2023年9月21日 857点热度 0人点赞 0条评论

用C#封装一个线程安全的缓存器,达到目标定时更新

错峰缓存,减少数据库IO瓶颈。

using System.Collections.Concurrent;
using Tools;

namespace SpacePhoneAPI.BackTask
{
    public class CacheManager<T>
    {
        private static CacheManager<T>? _instance;
        private static readonly object LockObject = new object();
        private BlockingCollection<T> buffer;
        private int MaxCache = 100;

        public delegate Task MyEventHandler(List<T> list);
        public event MyEventHandler? UpdateDataEvent;

        public CacheManager(int maxCache)
        {
            MaxCache = maxCache;
            buffer = new BlockingCollection<T>(MaxCache);
        }

        public static CacheManager<T> GetInstance(int maxCache)
        {
            if (_instance == null)
            {
                lock (LockObject)
                {
                    if (_instance == null)
                    {
                        _instance = new CacheManager<T>(maxCache);
                    }
                }
            }
            return _instance;
        }

        public int GetCount()
        {
            return buffer.Count;
        }

        /// <summary>
        /// 添加数据,触发被动更新
        /// </summary>
        /// <returns></returns>
        public void AddData(T data)
        {
            buffer.Add(data);
            NLogHelper.Debug("debug:" + buffer.Count.ToString());
            if (buffer.Count >= MaxCache)
            {
                UpdateDataEvent?.Invoke(buffer.ToList());
                buffer.Clear();
            }


        }

        /// <summary>
        /// 主动更新
        /// </summary>
        /// <returns></returns>
        public async Task InitiativeUpdate()
        {
            await Task.Run(() =>
            {
                if (buffer.Count > 0)
                {
                    UpdateDataEvent?.Invoke(buffer.ToList());
                    buffer.Clear();
                }
            });
        }
    }
}

扩展方法

public static class ExtendBlockingCollection
{
    public static void Clear<T>(this BlockingCollection<T> blockingCollection)
    {
        if (blockingCollection == null)
        {
            throw new ArgumentNullException("blockingCollection");
        }

        while (blockingCollection.Count > 0)
        {
            T item;
            blockingCollection.TryTake(out item);
        }
    }
}

 

试用测试:

var cache = CacheManager<int>.GetInstance(10);
cache.UpdateDataEvent += Cache_UpdateDataEvent;

for (int i = 0; i < 100; i++)
{
    cache.AddData(i);
    Console.WriteLine($"Add:" + i);
}
Console.ReadKey();

async Task Cache_UpdateDataEvent(List<int> list)
{
    await Task.Delay(TimeSpan.FromSeconds(1));
    string tt = "";
    foreach (var item in list)
        tt += item + ",";

    Console.WriteLine($"Inserted into database:" + tt);
}

 

标签: 暂无
最后更新:2023年9月21日

博主

全栈工程师,侧重项目技术解决方案规划和开发

打赏 点赞
< 上一篇
下一篇 >

文章评论

取消回复

分类
  • .NET (65)
  • docker (3)
  • linux (12)
  • python (20)
  • web (14)
  • 小程序 (4)
  • 数据库 (2)
  • 未分类 (4)
  • 杂七杂八 (10)
标签聚合
DevExpress js nginx centos python winform linux C#
最新 热点 随机
最新 热点 随机
.NET开发手册标准参考 招募兼职前端开发 Centos安装dotnet6环境 VS上切换分支,vs编译运行出现bug,A fatal error was encountered彻底解决方案 用C#封装一个线程安全的缓存器,达到目标定时定量更新入库 C#通过特性的方式去校验指定数据是否为空
前端VUE调用接口下载execl出现乱码打不开的问题 python 多线程和多进程 python 批量剪切图片指定区域 用C#写基于用户的协同过滤算法,推荐网站上你可能感兴趣的人 错误处理 ssh登陆提示:server unexpectedly closed network connection centos 运行php

COPYRIGHT © 2021 陈程的技术博客. ALL RIGHTS RESERVED.

THEME KRATOS MADE BY VTROIS