代码改变世界

C#并行编程之数据并行

2016-11-28 14:40  sql_manage  阅读(682)  评论(0编辑  收藏  举报

所谓的数据并行的条件是:

      1、拥有大量的数据。

      2、对数据的逻辑操作都是一致的。

      3、数据之间没有顺序依赖。

运行并行编程可以充分的利用现在多核计算机的优势。记录代码如下:

 public class ParallerFor
    {
        public List<string> studentList;

        public ParallerFor() {
            this.studentList = new List<string>();
            for (int i = 0; i < 50; i++) {
                this.studentList.Add("xiaochun"+i.ToString());
            }
        }

        public void ParallerTest() {
            var sw = Stopwatch.StartNew();
            foreach (string str in this.studentList) {
                Console.WriteLine("this is sync "+str);
                Thread.Sleep(800);
            }
            Console.WriteLine("运行时间:"+sw.Elapsed.ToString());
        }

        public void ParallerAsyncTest() {
            var sw = Stopwatch.StartNew();
            Action<int> ac = (i) => { Console.WriteLine("this is async " + this.studentList[i]); Thread.Sleep(800); };
            Parallel.For(0, this.studentList.Count,ac);//这里的0是指循环的起点
            Console.WriteLine("运行时间:" + sw.Elapsed.ToString());
        }

        public void ParallalForEachTest() {
            var sw = Stopwatch.StartNew();
            Action<string> ac = (str) => {
                    int num = int.Parse(str.Replace("xiaochun",string.Empty));
                    if (num > 10) {
                        Console.WriteLine(str);
                        Thread.Sleep(1000);
                    }
            };
            //限定最大并行数目
            ParallelOptions op = new ParallelOptions();
            op.MaxDegreeOfParallelism = 4;
            Parallel.ForEach(this.studentList,op,ac);
            //这里没有限定最大并行数目
            //Parallel.ForEach(this.studentList,ac);
        }

    }