110,534
社区成员
发帖
与我相关
我的任务
分享
public void ParallelBreak()
{
Console.WriteLine("\n————— {0} —————", MethodBase.GetCurrentMethod().Name);
ConcurrentBag<int> bag = new ConcurrentBag<int>();
stopWatch.Start();
Parallel.For(0, 1000, (i, state) =>
{
//此处加 lock (bag) 则输出一定是 300. 否则不一定是 300 , 可能是 302, 300, 306 等
if (bag.Count >= 300)
{
state.Stop();
return;
}
bag.Add(i);
});
stopWatch.Stop();
Console.WriteLine("Bag count is " + bag.Count + ", " + stopWatch.ElapsedMilliseconds);
}
public static void ListWithParallel()
{
Console.WriteLine("————— {0} —————", MethodBase.GetCurrentMethod().Name);
List<int> list = new List<int>();
Parallel.For(0, 10000, item =>
{
list.Add(item);
});
Console.WriteLine("List's count is {0}", list.Count());
}