原文地址:
http://www.cnblogs.com/dxy1982/p/3640210.html
http://blog.csdn.net/yl2isoft/article/details/12232935
https://msdn.microsoft.com/zh-cn/library/dd287108.aspx
ConcurrentDictionary<TKey, TValue> 类
ConcurrentQueue<T> 类
ConcurrentStack<T> 类
示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Threading;
namespace ConcurrentCollectionsTest
{
class Program
{
static ConcurrentBag<int> list;
static void Main(string[] args)
{
list = new ConcurrentBag<int>();
for (int i = 0; i < 10; i++)
{
list.Add(i);
}
Thread t1 = new Thread(Function1);
Thread t2 = new Thread(Function2);
t1.Start();
t2.Start();
Console.ReadKey();
}
static void Function1()
{
foreach (var item in list)
{
Console.WriteLine("t1.item:{0}", item);
Thread.Sleep(1000);
}
}
static void Function2()
{
Thread.Sleep(1000);
int a;
list.TryTake(out a);
foreach (var item in list)
{
Console.WriteLine("t2.item:{0}", item);
Thread.Sleep(200);
}
}
}
}
小结:
1、Concurrent Collections是无锁的,使用SpinWait、Interlocked等原子级的同步方法,效率高于普通集合手动加锁的方式
2、Concurrent Collections每次遍历的是集合当时的一个片段,不会阻止其他线程修改集合,同样的,其他线程修改集合也不会影响进行中的遍历