
DotNet高性能设备索引实现(多线程安全+效率)
发布日期:2021-05-10 13:51:58
浏览次数:15
分类:精选文章
本文共 4178 字,大约阅读时间需要 13 分钟。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ThreadTest{ class Program { private static string GuidStr = string.Empty; private static DictionaryDatas = new Dictionary (); static void Main(string[] args) { List threads = new List (); for (int i = 0; i < 10000; i++) { GuidStr = Guid.NewGuid().ToString(); var dataCache = new DataCache { Name = GuidStr, Value = "123456789" }; if (Datas.TryGetValue(GuidStr, out var tempDataCache)) { Datas[GuidStr] = dataCache; } else { Datas.Add(GuidStr, dataCache); } } for (int i = 0; i < 1000; i++) { var thread = new Thread(Check); thread.Start(); threads.Add(thread); } for (int i = 0; i < 10; i++) { var thread = new Thread(Amend); thread.Start(); threads.Add(thread); } Thread.Sleep(10000); foreach (var thread in threads) { try { thread.Abort(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } Console.WriteLine("Exit"); } private static void Amend() { while (true) { var dataCache = Get(GuidStr); if (dataCache != null) { dataCache.Value = "123456789"; Thread.Sleep(1000); if (dataCache != null) { dataCache.Value = "987654321"; Thread.Sleep(1000); if (dataCache != null) { dataCache.IsDelete = true; Thread.Sleep(1000); if (dataCache != null) { dataCache.IsDelete = false; } } } } } } private static void Check() { while (true) { var dataCache = Get(GuidStr); if (dataCache != null) { if (dataCache.IsDelete) { Console.WriteLine("IsDelete == True"); } else { if (dataCache.Value == "123456789") { Console.WriteLine("IsDelete == False, Value == 123456789"); } else if (dataCache.Value == "987654321") { Console.WriteLine("IsDelete == False, Value == 987654321"); } else { Console.WriteLine("Error"); } } } else { Console.WriteLine("dataCache == null"); } Thread.Sleep(10); } } private static DataCache Get(string guidStr) { DataCache dataCache; if (Datas.TryGetValue(guidStr, out dataCache)) { return dataCache; } else { return null; } } } public class DataCache { public string Name { get; set; } public string Value { get; set; } public bool IsDelete { get; set; } }}
发表评论
最新留言
路过,博主的博客真漂亮。。
[***.116.15.85]2025年04月21日 03时59分44秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
实现营销号生成器
2021-05-10
centos7安装mysql,以及密码设置.
2021-05-10
gunicorn配置文件的启动方式
2021-05-10
STM32 GPIO 配置之ODR, BSRR, BRR 详解
2021-05-10
C#实现简单音乐播放器
2021-05-10
Ubuntu windows双系统没有引导界面的解决办法
2021-05-10
如何复制百度文库内容?
2021-05-10
Opencv视觉学习--读取、写入、显示图像
2021-05-10
Opencv视觉学习--调用摄像头、显示视频图像
2021-05-10
编写一个程序,检测当前系统的进程最多能打开几个文件。
2021-05-10
(顺序栈 / 链式栈)编程实现功能:将十进制数,分别转换为八进制和十六进制。
2021-05-10
C语言生成N个随机数组并存入txt文本文件
2021-05-10
虚拟机Ubuntu系统重启出现initramfs的解决办法
2021-05-10
Linux安装 Redis 以及配置
2021-05-10
一维多项式计算
2021-05-10
两数和
2021-05-10
linux之Shell
2021-05-10
SpringBoot整合Exception实现异常处理
2021-05-10
Vue实现当前页面表格列表中的数据按时间排序sorter
2021-05-10