1、泛型集合Dictionary<TKey, Tvalue>
.NET中Dictionary<TKey, Tvalue>是非常常用的key-value的数据结构,表示键和值的集合,也就是哈希表。
每次对字典的添加都包含一个值和与其关联的键。使用键检索值的速度非常快,接近O(1)。
//必须包含c#泛型命名空间
using System.Collections.Generic;
//实例化:Dictionary<键key,值value> 名字dic=new Dictionary<键key,值value>();
Dictionary<Tkey,Tvalue> Data = new Dictionary<Tkey,Tvalue>();
//增:Data.Add(key,value)将指定的键和值添加到字典中
Data.Add("name","Johe");
Data.Add("from","henan");
Data.Add("sex","Man");
//查:Data[key]表示key所对应的值
if(Data.ContainsKey("name"))
{
string text =Data["name"];
}
//遍历Key和Value
foreach(string key in Data.Keys)
{
Console.WriteLine("" + key.ToString());
}
foreach(string value in Data.Values)
{
Console.WriteLine("" + value.ToString());
}
//改:
Data[from] = "hebei";
Console.WriteLine("" + Data[from].ToString());
//删:Data.Remove(key) 删除指定值
//判断空:Data.ContainsKey(key) 判断key是否存在
openWith.Remove("doc");
if (!openWith.ContainsKey("doc"))
{
Console.WriteLine("Key \"doc\" is not found.");
}
要找到所写的代码中无处不在的Dictionary,用于读取或写入,并使用同步原语(syncronisation primitive),例如锁 ,以确保任何时候只在单个线程访问它:
private readonly object padlock = new object();
private readonly Dictionary<string, object> dictionary = new Dictionary<string, object>();
private void Test()
{
object myValue;
// Now we lock before we do anything
lock (padlock)
{
if (dictionary.ContainsKey("Testing"))
{
myValue = dictionary["Testing"];
}
}
lock (padlock)
{
if (!dictionary.TryGetValue("Testing", out myValue)) { }
}
}
2、SafeDictionary<TKey, Tvalue>组合(组合设计模式的实现)
在这种方法中,总结了我们在自己的类中使用讨厌地非线程安全的Dictionary,让我使用想用的方法,并采取相应的任何锁。 这个类只实现了“array” 的访问和TryGetValue,但是这个方法足够用了:
public class SafeDictionary<TKey, TValue>
{
private readonly object _Padlock = new object();
private readonly Dictionary<TKey, TValue> _Dictionary = new Dictionary<TKey, TValue>();
public TValue this[TKey key]
{
get
{
lock (_Padlock)
{
return _Dictionary[key];
}
}
set
{
lock (_Padlock)
{
_Dictionary[key] = value;
}
}
}
public bool TryGetValue(TKey key, out TValue value)
{
lock (_Padlock)
{
return _Dictionary.TryGetValue(key, out value);
}
}
}
当我们防止任何直接进入Dictionar和每当我们需要访问它并在内部使用我们的锁的时候,我们现在可以使用代码SafeDictionary无需担心并发问题,无论是读和写操作。
所以当我需要使用内部字典来存储客户 “注册” 的数据时,可以避免依赖锁定周围的每一个访问。
public class testData<TKey, TValue>
{
private static readonly object mutex = new object();
public SafeDictionary<TKey, TValue> Datas { get; private set; } = new SafeDictionary<TKey, TValue>();
protected emCache()
{
}
private static testData<TKey, TValue> a = null;
public static testData<TKey, TValue> A
{
get
{
lock (mutex)
{
if (a == null) a = new testData<TKey, TValue>();
return a;
}
}
}
}
参考文档: