.net concurrency(parallel) -data concurrency foreach

 
  static void Main(string[] args)
        {
            int[] arr= new int[1000];
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = i;
            }

            //sequential ForEach
            int b = 0;
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            foreach (var x in arr)
            {
                b = b + x;
                System.Threading.Thread.Sleep(1);
                //Console.WriteLine(x);
            }
            stopwatch.Stop();
            Console.WriteLine("Sequential loop time in milliseconds: {0} ,value of b:{1}", stopwatch.ElapsedMilliseconds,b);

            //currency ForEach
            b = 0;
            stopwatch.Reset();
            stopwatch.Start();
            Console.WriteLine("-------------------");
                Parallel.ForEach(arr,
                        (x) =>
                        {
                            //lock
                            /*
                            var t = "";
                            lock(t){
                                b = b + x;
                            }
                            
*/
                            Interlocked.Add(ref b,x);
                            System.Threading.Thread.Sleep(1);
                            //Console.WriteLine(x);
                        }
                    );
                stopwatch.Stop();
                Console.WriteLine("Concurrency loop time in milliseconds: {0} ,value of b:{1}", stopwatch.ElapsedMilliseconds,b);
            Console.Read();

        } 

 

 

http://msdn.microsoft.com/en-us/library/dd460717.aspx 

 

http://msdn.microsoft.com/en-us/library/ff963552.aspx 

 

posted @ 2012-08-10 11:26  zyip  阅读(185)  评论(0编辑  收藏  举报