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": { " ...
随机推荐
- 20_java之集合Map
01Map集合概述 A:Map集合概述: 我们通过查看Map接口描述,发现Map接口下的集合与Collection接口下的集合,它们存储数据的形式不同 a:Collection中的集合,元素是孤立 ...
- short i=1;short i=i+1对或错,错的理由;short i+=1对或错,错的理由
short i=1; i=i+1 i+=1 这是一个类型高级与低级的问题,前面的C是short型的,后面的1为int型的,short型与int型的相加得到short型是不可取,因为必须将int型转换为 ...
- 【原】Coursera—Andrew Ng机器学习—Week 9 习题—异常检测
[1]异常检测 [2]高斯分布 [3]高斯分布 [4] 异常检测 [5]特征选择 [6] [7]多变量高斯分布 Answer: ACD B 错误.需要矩阵Σ可逆,则要求m>n 测验1 Answ ...
- java web 读取配置文件两种方法
package com.tsinghua.getDataBaseConn; import java.io.IOException;import java.io.InputStream;import j ...
- css常用属性总结之 id和class的区别,使用类还是ID?
前面两篇文章我们分别谈到了class和id的相关知识和如何使用,但是在实际项目中,我们该如何抉择,class还是id? 先回顾下两者的区别吧! 1.id具有唯一性,class具有普遍性,所以一个页面同 ...
- Spark internal - 多样化的运行模式 (下)
Spark的各种运行模式虽然启动方式,运行位置,调度手段有所不同,但它们所要完成的任务基本都是一致的,就是在合适的位置安全可靠的根据用户的配置和Job的需要管理和运行Task,这里粗略的列举一下在运行 ...
- 高性能Web服务器Nginx的配置与部署研究(8)核心模块之事件模块
一.事件模块的作用是什么? 用来设置Nginx处理链接请求. 二.相关指令 1. accept_mutex 含义:设置是否使用连接互斥锁进行顺序的accept()系统调用. 语法:accept_mut ...
- 对加密的了解(DES/3DES/AES区别 )
DES 1977年1月,美国政府颁布:采纳IBM公司设计的方案作为非机密数据的正式. 目前在国内,随着三金工程尤其是金卡工程的启动,DES算法在POS.ATM.磁卡及智能卡(IC卡).加油站.高速公路 ...
- Spring Data JPA + layui的前台分页插件layPage实现页面的分页
一.后台代码: 1.1 controller层代码 @RequestMapping("/xxxxxx") public String showInformationCode(Str ...
- 配置jdk和tomcat的环境变量
一.1,新建变量名:JAVA_HOME,变量值:d:\Program Files\Java\jdk1.7.0 2,打开PATH,添加变量值:%JAVA_HOME%\bin;%JAVA_HOME%\jr ...