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": { " ...
随机推荐
- linux命令日志处理
刘超 2018/10/8 10:32:43 zcat bi_www_activity_2018100*.log.gz |grep --color '多方电话h5_' | awk -F'|' '{pri ...
- GIL与线程、进程、协程
GIL全局解释器锁: 1.相信大家都知道python代码是不能直接被机器cpu识别和执行的,它要经过python解释器(也就是我们执行时候的python3 name.py)被编译成机器语言,pytho ...
- LR11中webservice协议的性能测试应用
使用LR11对webservice协议的接口测试应用 脚本开发步骤:1.打开vuser generator,新建一个脚本,选择webservice协议:2.选择Manage Services(服务管理 ...
- python中的socket模块
熟悉了一下python的socket模块,感觉还是有点好玩的,不过坑也也是不少的. 1.服务器端代码 #!/usr/bin/env python import socket HOST='192.168 ...
- git之GitHub Pages
git之GitHub Pages GitHub Pages是github的一项很实用的功能,它可以让我们将github里面的静态网站的代码在线上展示出来,可以用来做项目展示和个人博客的载体. 1.将 ...
- winform 实现局部更新(如ajax实现)而整个界面不产生闪烁的解决方案
转自原文winform 实现局部更新(如ajax实现)而整个界面不产生闪烁的解决方案 一.通过对窗体和控件使用双缓冲来减少图形闪烁(当绘制图片时出现闪烁时,使用双缓冲) 对于大多数应用程序,.NET ...
- 【302】C# TreeView 控件使用说明
参考:C# 中treeview 树节点图标的动态加载,及选中时图标改变 参考:C# TreeView 控件的综合使用方法 参考:TreeView 类 参考:TreeNode 类 1. 添加根和子级 通 ...
- ubuntu kylin 设置 wifi
左上侧 搜索资源 输入 软件和更新 点击软件和更新,点击附加驱动,点击使用无线驱动.
- 第五章 大数据平台与技术 第13讲 NoSQL数据库
NoSQL不是不用SQL,是Not only SQL,不仅仅是结构化的查询. NoSQL兴起的原因 在Web2.0时代新浪一分钟可以发送两万条微博,苹果可以下载4.7万次应用. 数据的高并发性,同时有 ...
- android-tip-各种clock的使用
参考:http://developer.android.com/reference/android/os/SystemClock.html System.currentTimeMills() 这个函 ...