• C#并行编程之数据并行


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

          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);
            }
    
        }
  • 相关阅读:
    textarea 滚动条属性设置
    js触发asp.net的Button的Onclick事件
    Asp.Net获取远程数据并保存为文件的简单代码
    《WEB标准拾遗系列》
    .NET基础拾遗系列第一篇
    .NET基础拾遗系列第三篇
    你的知识如何管理(必须看)
    .NET基础拾遗系列第二篇
    随便划两笔
    Sql server 事务的两种用法 (转)
  • 原文地址:https://www.cnblogs.com/msql/p/6109459.html
Copyright © 2020-2023  润新知