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 Dictionary
Datas = 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; }
}
}
上一篇:IDEA导入Maven工程,导入Spring Boot框架工程
下一篇:2021-05-08

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2025年04月21日 03时59分44秒