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");
}
}
}热门推荐
10 医院探望朋友祝福语简短
11 毕业祝福语简短女朋友
12 春节虎年爸妈祝福语简短
13 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短