using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
public static void Main()
int tartgetCount = 10000;
List<string> list = new List<string>();
Console.WriteLine("預期List有 {0} 筆資料", tartgetCount);
ConcurrentQueue<Exception> exceptions = new ConcurrentQueue<Exception>();
Parallel.For(0, tartgetCount, (i, loopState) =>
list.Add(new Random().NextDouble().ToString());
catch (IndexOutOfRangeException e)
Console.WriteLine(exceptions.First().ToString());
Console.WriteLine("實際List有 {0} 筆資料(沒有用Lock): ", list.Count());
list = new List<string>();
Object _lock = new Object();
Parallel.For(0, tartgetCount, (i, loopState) =>
list.Add(new Random().NextDouble().ToString());
Console.WriteLine("實際List有 {0} 筆資料(有用Lock): ", list.Count());
ConcurrentBag<string> stack = new ConcurrentBag<string>();
Parallel.For(0, tartgetCount, (i, loopState) =>
stack.Add(new Random().NextDouble().ToString());
Console.WriteLine("實際Stack有 {0} 筆資料: ", stack.Count());