ConcurrentDictionary 与 Dictionary
public interface IGetLogger
{
string GetLogger(string cmdId);
}
2. Dictionary 实现:
public class DictionaryLogger : IGetLogger
{
static Dictionary<string, string> loggreDic = new Dictionary<string, string>();
public string GetLogger(string cmdId)
{
if (!loggreDic.ContainsKey(cmdId))
{
loggreDic.Add(cmdId, $"AAA.{cmdId}");
}
return loggreDic[cmdId];
}
}
public class ConcurrentDictionaryLogger : IGetLogger
{
static ConcurrentDictionary<string, string> loggreDic = new ConcurrentDictionary<string, string>(); public string GetLogger(string cmdId)
{
if (!loggreDic.ContainsKey(cmdId))
{
loggreDic.TryAdd(cmdId, $"ConcurrentDictionary.{cmdId}");
}
return loggreDic[cmdId];
}
}
public partial class ConcurrentDictionaryForm : Form
{
public ConcurrentDictionaryForm()
{
Console.WriteLine("欢迎来到ConcurrentDictionary线程安全");
InitializeComponent();
} /// <summary>
/// 非线程安全
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Dictionary_Click(object sender, EventArgs e)
{
int threadCount = ;
CountDownLatch latch = new CountDownLatch(threadCount);
object state = new object();
for (int i = ; i < threadCount; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(new WasteTimeDic(latch).DoSth), i);
}
latch.Await();
} /// <summary>
/// 线程安全
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ConcurrentDictionary_Click(object sender, EventArgs e)
{ int threadCount = ; CountDownLatch latch = new CountDownLatch(threadCount);
object state = new object();
for (int i = ; i < threadCount; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(new WasteTime(latch).DoSth), i);
}
latch.Await(); } }
CountDownLatch 是一个自定义个的并发检测类:
public class CountDownLatch
{
private object lockObj = new Object();
private int counter; public CountDownLatch(int counter)
{
this.counter = counter;
} public void Await()
{
lock (lockObj)
{
while (counter > )
{
Monitor.Wait(lockObj);
}
}
} public void CountDown()
{
lock (lockObj)
{
counter--;
Monitor.PulseAll(lockObj);
}
}
} public class WasteTime
{
private CountDownLatch latch; public WasteTime(CountDownLatch latch)
{
this.latch = latch;
} public void DoSth(object state)
{
//模拟耗时操作
//System.Threading.Thread.Sleep(new Random().Next(5) * 1000);
//Console.WriteLine("state:"+ Convert.ToInt32(state)); IGetLogger conLogger = new ConcurrentDictionaryLogger();
try
{
Console.WriteLine($"{state}GetLogger:{conLogger.GetLogger("BBB")}");
}
catch (Exception ex)
{
Console.WriteLine(string.Format("第{0}个线程出现问题", state));
}
//执行完成注意调用CountDown()方法
this.latch.CountDown();
} } public class WasteTimeDic
{
private CountDownLatch latch; public WasteTimeDic(CountDownLatch latch)
{
this.latch = latch;
} public void DoSth(object state)
{
//模拟耗时操作
//System.Threading.Thread.Sleep(new Random().Next(5) * 1000);
//Console.WriteLine("state:"+ Convert.ToInt32(state));
IGetLogger conLogger = new DictionaryLogger();
try
{
Console.WriteLine($"{state}GetLoggerDic:{conLogger.GetLogger("AAA")}");
}
catch (Exception ex)
{
Console.WriteLine(string.Format("第{0}个线程出现问题", state));
}
//执行完成注意调用CountDown()方法
this.latch.CountDown();
} }
会有一定几率出现异常情况:
ConcurrentDictionary 与 Dictionary的更多相关文章
- ConcurrentDictionary与Dictionary 替换
本文导读:ASP.NET中ConcurrentDictionary是.Net4 增加的,相对于Dictionary的线程安全的集合, ConcurrentDictionary可实现一个线程安全的集合, ...
- ConcurrentDictionary 对决 Dictionary+Locking
在 .NET 4.0 之前,如果我们需要在多线程环境下使用 Dictionary 类,除了自己实现线程同步来保证线程安全之外,我们没有其他选择. 很多开发人员肯定都实现过类似的线程安全方案,可能是通过 ...
- ConcurrentDictionary和Dictionary
http://stackoverflow.com/questions/6739193/is-the-concurrentdictionary-thread-safe-to-the-point-that ...
- 浅谈ConcurrentDictionary与Dictionary
在.NET4.0之前,如果我们需要在多线程环境下使用Dictionary类,除了自己实现线程同步来保证线程安全外,我们没有其他选择.很多开发人员肯定都实现过类似的线程安全方案,可能是通过创建全新的线程 ...
- 改进ConcurrentDictionary并行使用的性能
上一篇文章“ConcurrentDictionary 对决 Dictionary+Locking”中,我们知道了 .NET 4.0 中提供了线程安全的 ConcurrentDictionary< ...
- ConcurrentDictionary<TKey, TValue>的AddOrUpdate方法
https://msdn.microsoft.com/zh-cn/library/ee378665(v=vs.110).aspx 此方法有一共有2个,现在只讨论其中一个 public TValue A ...
- ConcurrentDictionary并发字典知多少?
背景 在上一篇文章你真的了解字典吗?一文中我介绍了Hash Function和字典的工作的基本原理. 有网友在文章底部评论,说我的Remove和Add方法没有考虑线程安全问题. https://doc ...
- 1、C#中Hashtable、Dictionary详解以及写入和读取对比
在本文中将从基础角度讲解HashTable.Dictionary的构造和通过程序进行插入读取对比. 一:HashTable 1.HashTable是一种散列表,他内部维护很多对Key-Value键值对 ...
- Encountered an unexpected error when attempting to resolve tag helper directive '@addTagHelper' with value '"*, Microsoft.AspNet.Mvc.TagHelpers"'
project.json 配置: { "version": "1.0.0-*", "compilationOptions": { " ...
随机推荐
- php header 302重定向失效问题
E:\html\pim\php_weili_activities\application\controllers\user.php public function login() { if ($thi ...
- 用VIM设置UTF-8编码的BOM标记
1.去掉BOM标记: :set nobomb 2.加上BOM标记: :set bomb 3.查询当前UTF-8编码的文件是否有BOM标记: :set bomb? 4.更高级一点的: :%!xxd &q ...
- 本地YUM仓库搭建实战
YUM主要用于自动安装.升级rpm软件包,它能自动查找并解决rpm包之间的依赖关系.要成功的使用YUM工具安装更新软件或系统,就需要有一个包含各种rpm软件包的repository(软件仓库),这个软 ...
- 【Oracle】Oracle数据库DATABASE LINK 的命名
当前数据库的GLOBAL_NAMES参数设置为 TRUE,使用DATABASE LINK 时,DATABASE LINK的名称必须与被连接库的 GLOBAL_NAME一致. 而要建多个 DBLINK到 ...
- HTTP接口开发专题一(四种常见的 POST 提交数据方式对应的content-type取值)
application/x-www-form-urlencoded 这应该是最常见的 POST 提交数据的方式了.浏览器的原生 form 表单,如果不设置 enctype 属性,那么最终就会以 app ...
- 浅谈AVL树,红黑树,B树,B+树原理及应用(转)
出自:https://blog.csdn.net/whoamiyang/article/details/51926985 背景:这几天在看<高性能Mysql>,在看到创建高性能的索引,书上 ...
- Django一些技巧
整数限制范围 from django.core.validators import MaxValueValidator, MinValueValidator start = models.Intege ...
- flask 数据迁移
python flasky.py shell db.create_all() from app.models import User mhc = User("mhc") >& ...
- vmvare centos7 切换桌面和命令行模式
systemctl set-default multi-user.target 命令行 systemctl set-default graphical.target 桌面
- AlphaTesting
[Alpha Testing] The alpha test is a last chance to reject a pixel from being written to the screen. ...