ConcurrentBag 集合
表示對象的線程安全的無序集合。
static void Main(string[] args)
{
ConcurrentBag<int> thList = new ConcurrentBag<int>();
Parallel.For(0, 100000, a =>
{
thList.Add(a);
});
thList.TryPeek(out int result1); //獲取末尾的值
Console.WriteLine(string.Format("Count:{0} Result:{1}", thList.Count, result1));
thList.TryTake(out int result2); //刪除並獲取末尾的值
Console.WriteLine(string.Format("Count:{0} Result:{1}", thList.Count, result2));
Console.ReadKey();
}
注:若是使用List<int>,在並行添加數據時要么會拋異常要么集合中的個數不對。
PS:ConcurrentBag<T>不能像List<T>一樣輕易獲取任何索引處的值和刪除任意一個值。 若要使用獲取和刪除,請使用ConcurrentDictionary。
ConcurrentDictionary 字典
static void Main(string[] args)
{
ConcurrentDictionary<int, int> thDict = new ConcurrentDictionary<int, int>();
Parallel.For(0, 10, a =>
{
bool isOK = thDict.TryAdd(a, a);
if (thDict.ContainsKey(4))
{
thDict[4] = 400;
}
});
Console.WriteLine(string.Format("Count:{0} Values:{1}", thDict.Count, string.Join(",", thDict.Values)));
thDict.TryRemove(3, out int value);
Console.WriteLine(string.Format("Count:{0} value:{1} Values:{2}", thDict.Count, value, string.Join(",", thDict.Values)));
Console.ReadKey();
}
ConcurrentQueue 隊
表示線程安全的先進先出 (FIFO) 集合。
static void Main(string[] args)
{
ConcurrentQueue<int> thQueue = new ConcurrentQueue<int>();
Parallel.For(0, 10, a =>
{
thQueue.Enqueue(a);
});
thQueue.TryPeek(out int result1); //獲取開頭處的對象
thQueue.TryDequeue(out int result2); //獲取開頭處的對象並將其移除
Console.ReadKey();
}
ConcurrentStack 棧
表示線程安全的后進先出 (LIFO) 集合。
static void Main(string[] args)
{
ConcurrentStack<int> thQueue = new ConcurrentStack<int>();
Parallel.For(0, 10, a =>
{
thQueue.Push(a);
});
thQueue.TryPeek(out int result1); //獲取頂部的對象
thQueue.TryPop(out int result2); //獲取頂部的對象並將其移除
Console.ReadKey();
}