在C#里面我们常用各种集合、数组、List、Dictionary、Stack等,然而这些集合都是非线程安全的,当多线程同时读写这些集合的时候,有可能造成里面的数据混乱,为此微软从Net4.0开始专门提供了另一套线程安全类型,放在System.Collections.Concurrent命名空间中,我们这里以ConcurrentDictionary<T, T>为例进行讲解。
一、TryUpdate()方法讲解
obj.TryUpdate("count",1,0);执行逻辑:如果obj["count"]==0,则将obj["count"]的值更新为1+返回值为true,否则不更新obj["count"]的值+返回值为false,因为此时obj["count"]值为0所以更新成功
obj.TryUpdate("count",2,0);执行逻辑:如果obj["count"]==0,则将obj["count"]的值更新为2+返回值为true,否则不更新obj["count"]的值+返回值为false,因为此时obj["count"]值为1所以更新失败
TryUpdate()方法官方说明如下:
二、ConcurrentDictionary<T, T>如何保证线程安全
public static void Main(string[] args)
{
Console.WriteLine("[Main]ManagedThreadId=" + Thread.CurrentThread.ManagedThreadId);
ThreadSecurityType securityType = new ThreadSecurityType();
for (int i = 0; i < 10; i++)
{
Thread thread = new Thread(() =>
{
securityType.RunSafe();
});
thread.Start();
}
Console.ReadKey();
}
AddOrUpdate()源码如下: