C#中的线程安全并发集合
.NETFramework4带来了System.Collections.Concurrent命名空间。它具有几个线程安全和可伸缩的集合类。这些集合称为并发集合,因为它们一次可以被多个线程访问。
以下是C#中的并发集合-
任何类型的边界和阻止功能。
键值对字典的线程安全实现。
FIFO(先进先出)队列的线程安全实现。
LIFO(后进先出)堆栈的线程安全实现。
无序元素集合的线程安全实现。
类型必须实现以在BlockingCollection中使用的接口
让我们看看如何使用ConcurrentStack<T>,后者是线程安全的后进先出(LIFO)集合。
创建一个ConcurrentStack。
ConcurrentStack<int> s = new ConcurrentStack<int>();
添加元素
s.Push(1); s.Push(2); s.Push(3); s.Push(4); s.Push(5); s.Push(6);
让我们看一个例子
示例
using System;
using System.Collections.Concurrent;
class Demo{
static void Main (){
ConcurrentStack s = new ConcurrentStack();
s.Push(50);
s.Push(100);
s.Push(150);
s.Push(200);
s.Push(250);
s.Push(300);
if (s.IsEmpty){
Console.WriteLine("堆栈是空的!");
}
else {
Console.WriteLine("The stack isn't empty");
}
}
}