小编ato*_*hod的帖子

并行.失败(C#)

我写了一些代码:

class Program
    {
        public const int count = 3000;
        static List<int> list = new List<int>();
        static void DoWork(int i)
        {            
            list.Add(i);
        }        
        static void Main(string[] args)
        {
            while (true)
            {

                Stopwatch s = new Stopwatch();
                s.Start();
                Parallel.For(0, count + 1, DoWork);            
                s.Stop();
                Console.WriteLine("\n Elapsed: " + s.Elapsed.ToString());
                Console.WriteLine("Expected: {0}", count + 1);
                Console.WriteLine("count: {0}", list.Count);
                Console.ReadKey();
                list = new List<int>(); 
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

但结果不是预期的(

并非所有循环都在Console.WriteLine调用之前完成

使用Parallel.For有什么问题?

c# parallel-processing

4
推荐指数
1
解决办法
386
查看次数

标签 统计

c# ×1

parallel-processing ×1