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": { " ...
随机推荐
- Tkinter简易教程
支持python的常见GUI工具包: Tkinter 使用Tk平台 很容易得到 半标准 wxpython 基于wxWindows.跨平台越来越流行 Python Win 只能在Windows上使用 使 ...
- 有关DotNetBar设计样式和运行时的样式不一致的问题
可以在 窗体类构造函数的InitializeComponent后加上下面圈出的内容: this.EnableGlass = false; 参考文章 DotNetBar如何控制窗体样式
- Android Studio 2.3.3 调用asp.net webService实战(拒绝忽悠)
1.路径中不能包含localhost(本来想在本机调试,就是不行,没办法发布到远程服务器) 2.必须采用异步的办法(阻塞主线程的是肯定不行了) 3.以下是全部的源代码(毫不保留) package co ...
- qrcode——js生成二维码
1.引入 qrcode.min.js(点击下载demo) 2.html: <div id="qrcode"></div> js: var qrcode = ...
- linux命令详解2-文件管理,查看文件命令
1. cat命令(tac) ----连接文件,并打印出来(顺序打印)与tac命令类似只不过,tac命令是逆序打印 [语法] cat [OPTION]... [FILE]... [选项] -A:显示所有 ...
- 封装baseservice
package com.huawei.base; import java.io.Serializable;import java.util.List; public abstract class Ba ...
- python操作符重载
操作符重载的魔术方法 操作符 方法 取反 即席 + __add__ __radd__ __iadd__ - __sub__ __rsub__ __isub__ * __mul__ __rmul__ _ ...
- 【poj1743】Musical Theme 【后缀自动机】
题意 给出一个n个数字的序列,找出相同变化趋势且不重叠的两个最长子串. 分析 这个题以前应该用后缀数组+二分做过.学了后缀自动机后可以用后缀自动机搞一下. 先差分,然后把查分后的数组建SAM.然后对于 ...
- 从Oracle数据库中查询与某一时间点最接近的记录
select * from data_taskregionschedule WHERE regioncode='HYL' and updatetime-to_date('2018-05-15','yy ...
- Kubuntu上连接PPTP
生活在天朝,如果没备几招FQ的本领,都不敢说自己还活着... 前两天从朋友那抢了个VPN帐号,使用的是PPTP的,在google上找了一会,发现网上大都是讲VPN服务搭建的,就算是介绍客户端的,也大都 ...