在线程中使用List会出现线程安全的问题,导致出现超出认知的问题。。。

所以线程中要把List替换成ConcurrentBag,ConcurrentBag是.NET 4.0中引入的线程安全集合之一。


/* 从List赋值到ConcurrentBag */

ConcurrentBag<int> bag = new ConcurrentBag<int>();


List<int> ints = new List<int>();

ints.Add(1);

ints.Add(2);

ints.Add(3);

ints.Add(4);


ConcurrentBag<int> bag = new ConcurrentBag<int>(ints);

int count = bag.Count; 



/* 创建ConcurrentBag,并添加项 */

ConcurrentBag<int> bag = new ConcurrentBag<int>();

bag.Add(1);

bag.Add(2);



/* 【TryPeek】 方法从包中返回一项,但不会从包中删除项。如果成功检索项目,则返回 true,否则返回 false。它返回 out 参数中的项目,如下例所示。 */

/* 由于 TryPeek 方法不会从包中删除项目,它会一次又一次地返回相同的最后一个项目。 */

ConcurrentBag<int> bag = new ConcurrentBag<int>();

bag.Add(1);

bag.Add(2);

 

int item;

bool isSucess = bag.TryPeek(out item); /* isSuccess=True, item = 2 */

isSuccess = bag.TryPeek(out item); /* isSuccess=True, item = 2 */

isSuccess = bag.TryPeek(out item); /* isSuccess=True, item = 2 */



/* 【TryTake】 方法从包中返回一个项目并将该项目从包中移除。如果成功检索项目,则返回 true,否则返回 false。 */

ConcurrentBag<int> bag = new ConcurrentBag<int>();

bag.Add(1);

bag.Add(2);

 

int item;

bool isSuccess = bag.TryTake(out item); /* isSuccess=True, item = 2 */

isSuccess = bag.TryTake(out item); /* isSuccess=True, item = 1 */


-- 由于 ConcurrentBag 实现了 IEnumerable 接口,我们可以在 foreach 循环中对其进行枚举。