예제 #1
0
 public void UpdateDevice(BcDevices bcDevices)
 {
     if (bcDevices == null)
     {
         throw new ArgumentNullException();
     }
     if (this._device != null && bcDevices.Id != this._device.Id)
     {
         throw new InvalidOperationException("bcDevices.Id != _device.Id");
     }
     if (!this.HasDifferProperties(bcDevices))
     {
         return;
     }
     lock (this._processingWorkers)
     {
         ParallelEnumerable.ForAll <Worker>(ParallelEnumerable.AsParallel <Worker>((IEnumerable <Worker>) this._processingWorkers), (Action <Worker>)(worker => worker.Pause()));
         this._device = bcDevices;
         this._detectionConfiguration = new DetectionConfiguration()
         {
             MinFace            = (uint)this._device.MinFace,
             DetectionThreshold = (double)this._device.DetectorScore
         };
         this.SyncProcessorCount();
         ParallelEnumerable.ForAll <Worker>(ParallelEnumerable.AsParallel <Worker>((IEnumerable <Worker>) this._processingWorkers), (Action <Worker>)(worker => worker.Resume()));
     }
 }
예제 #2
0
        public void MainTest()
        {
            var sw = new Stopwatch();

            sw.Start();
            var query = from t in GetTypes() select EmulateProcessing(t);

            foreach (string typeName in query)
            {
                PrintInfo(typeName);
            }
            sw.Stop();
            WriteLine(".........");
            WriteLine("Sequential LINQ query.");
            WriteLine($"Time elapsed:{sw.Elapsed}");
            WriteLine("Press ENTER to continue...");
            Console.Clear();
            sw.Reset();

            sw.Start();
            var parallelQuery = from t in ParallelEnumerable.AsParallel(GetTypes())
                                select EmulateProcessing(t);

            foreach (string typeName in parallelQuery)
            {
                PrintInfo(typeName);
            }
            sw.Stop();
            WriteLine(".......");
            WriteLine("Parallel Linq query. The results are being merged on singel thread");
            WriteLine($"Time elapsed:{sw.Elapsed}");
            WriteLine("Press ENTER to continue...");

            sw.Start();
            parallelQuery = from t in GetTypes().AsParallel()
                            select EmulateProcessing(t);

            parallelQuery.ForAll(PrintInfo);
            sw.Stop();
            WriteLine(".......");
            WriteLine("Parallel Linq query. The results are being merged on singel parallel");
            WriteLine($"Time elapsed:{sw.Elapsed}");
            WriteLine("Press ENTER to continue...");
            sw.Reset();

            sw.Start();
            query = from t in GetTypes().AsParallel().AsSequential()
                    select EmulateProcessing(t);

            foreach (var typeName in query)
            {
                PrintInfo(typeName);
            }
            sw.Stop();
            sw.Stop();
            WriteLine(".......");
            WriteLine("Parallel Linq query , transformed into sequential .");
            WriteLine($"Time elapsed:{sw.Elapsed}");
            WriteLine("Press ENTER to continue...");
        }
예제 #3
0
         public static NonParallelQuery AsParallel(this IEnumerable source)
         {
 #if DEBUG
             return new NonParallelQuery(ParallelEnumerable.AsParallel(source));
 #else
             return new NonParallelQuery(source);
 #endif
         }
예제 #4
0
        public static void Run()
        {
            var sw = new Stopwatch();

            sw.Start();
            var query = from t in GetTypes()
                        select EmulateProcessing(t);

            foreach (var typeName in query)
            {
                PrintInfo(typeName);
            }
            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Console.WriteLine("-----------------");
            //Console.Clear();

            sw.Reset();
            sw.Start();
            var parallelQuery = from t in
                                ParallelEnumerable.AsParallel(GetTypes())
                                select EmulateProcessing(t);

            foreach (var typeName in query)
            {
                PrintInfo(typeName);
            }
            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Console.WriteLine("-----------------");

            sw.Reset();
            sw.Start();
            parallelQuery = from t in GetTypes().AsParallel()
                            select EmulateProcessing(t);

            parallelQuery.ForAll(PrintInfo);
            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Console.WriteLine("-----------------");

            sw.Reset();
            sw.Start();
            query = from t in GetTypes().AsParallel().AsSequential()
                    select EmulateProcessing(t);

            foreach (var typeName in query)
            {
                PrintInfo(typeName);
            }
            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Console.WriteLine("-----------------");
        }
예제 #5
0
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            // 1
            var query = from p in GetProjects()
                        select ProcessProject(p);

            foreach (var name in query)
            {
                PrintProject(name);
            }
            sw.Stop();
            Console.WriteLine($"使用LINQ查询时间:{sw.ElapsedMilliseconds}");

            sw.Restart();
            // 2
            // 不同的线程处理不同的项目
            var parallelQuery = from p in ParallelEnumerable.AsParallel(GetProjects())
                                select ProcessProject(p);

            foreach (var name in parallelQuery)
            {
                PrintProject(name);
            }
            sw.Stop();
            Console.WriteLine($"使用PLINQ查询,查得的结果在一个线程上输出,总共花费时间:{sw.ElapsedMilliseconds}");

            sw.Restart();
            // 3
            // 单个处理项目和打印项目是同一个线程
            parallelQuery = from p in GetProjects().AsParallel() select ProcessProject(p);

            parallelQuery.ForAll(PrintProject);
            sw.Stop();
            Console.WriteLine($"使用PLINQ查询,查得的结果并行输出,总共花费时间:{sw.ElapsedMilliseconds}");

            sw.Restart();
            // 4 和第1种情况一样
            query = from p in GetProjects().AsParallel().AsSequential() select ProcessProject(p);

            foreach (var name in query)
            {
                PrintProject(name);
            }
            sw.Stop();
            Console.WriteLine($"使用PLINQ查询,转成顺序计算,查得的结果在一个线程上输出,总共花费时间:{sw.ElapsedMilliseconds}");


            Console.ReadKey();
        }
예제 #6
0
        public void UpdateForest(int optimizationSteps, float optimizationEps, float dt)
        {
            var allPlants  = ParallelEnumerable.AsParallel(plants);
            var allModules = allPlants.SelectMany(plant => plant.modules); // this merges all the modules into a single list

            UpdateBoundingSpheres(allModules);
            UpdateLight(allModules);
            UpdateVigor(allPlants);
            OptimizeRotation(allModules, optimizationSteps, optimizationEps);
            UpdatePhysiologicalAge(allModules, dt);
            GrowNewBranches(allModules);
            // Do this at the end since it removes some modules (so allModules won't be right)
            ShedBranches(allPlants, allModules);
        }
예제 #7
0
        public static void ShedBranches(ParallelQuery <Plant> allPlants, ParallelQuery <Module> allModules)
        {
            // Set as pruned
            allModules.ForAll(module =>
            {
                // Branches are shed if vigor is less than vigorRootMin
                if (module.root.v < module.plant.plantConfig.vigorRootMin)
                {
                    //module.isShed = true;
                }
            });

            // Remove all sheded modules from plants
            allPlants.ForAll(plant =>
            {
                plant.modules = ParallelEnumerable.AsParallel(plant.modules).Where(module => !module.isShed).ToList();
            });
        }
예제 #8
0
        public override void Run()
        {
            // PLINQ 是保守的,当不安全或并行不会提高查询效率时将默认使用顺序方法
            // ParallelEnumerable 编译在 System.Core.dll
            var models = this.CreateCollection(10);

            /* 串行转并行
             * 设置:
             * AsUnordered:抛弃顺序
             * WithMergeOptions:不缓存查询结果,查询出任一结果后立即返回
             * WithDegreeOfParallelism:并行度=处理器数量
             * WithExecutionMode:执行模式=并行优先
             */
            var pmodels = models.AsParallel()
                          .AsUnordered()
                          .WithMergeOptions(ParallelMergeOptions.NotBuffered)
                          .WithDegreeOfParallelism(Environment.ProcessorCount)
                          .WithExecutionMode(ParallelExecutionMode.ForceParallelism);
            // AsOrdered 并行时保留排序结果
            var pmodelOrdered = ParallelEnumerable.AsParallel(models).AsOrdered();

            _ = from model in models.AsParallel() select model;

            // 并行转串行
            _ = pmodels.AsSequential();
            _ = ParallelEnumerable.AsSequential(pmodels);
            _ = from model in pmodels.AsSequential() select model;

            // 并行输出
            Helper.PrintLine($"并行输出:{string.Join("、", pmodels.Select(m => m.Name))}");

            // ForAll
            pmodels.ForAll((m) => Helper.PrintLine($"并行执行:{m.Name}"));

            // 保留顺序 (可能会比直接顺序执行更慢)
            Helper.PrintLine($"保留顺序并行输出:{string.Join("、", pmodelOrdered.Select(m => m.Name))}");

            // 捕捉异常
            try
            {
                pmodels.ForAll(m => { if (m.Index % 2 == 1)
                                      {
                                          throw new ArgumentException();
                                      }
                               });
            }
            catch (AggregateException ex)
            {
                Helper.PrintLine($"PLINQ 遇到 {ex.InnerExceptions.Count} 个异常:{string.Join("\n", ex.InnerExceptions.Select(e => e.Message))}");
            }

            // 自定义聚合函数
            _ = pmodels.Aggregate(
                0,
                (sum, model) => { sum += model.Index; return(sum); },
                (sum, result) => { result += sum; return(result); },
                (result) => new RunModel(result));

            _ = pmodels.Aggregate(
                new RunModel(),
                (result, model) => { result.Index += model.Index; return(result); });
        }
예제 #9
0
파일: PLinqTools.cs 프로젝트: xeekst/C-
        public static void InvokeQuery()
        {
            var sw = new Stopwatch();

            sw.Start();
            var query = from t in GetTypes()
                        select EmulateProcessing(t);

            sw.Stop();
            //foreach (string typeName in query)
            //{
            //    PrintInfo(typeName);
            //}
            Console.WriteLine("----");
            Console.WriteLine("1Sequential LINQ query");
            Console.WriteLine("Time elapsed:{0}", sw.Elapsed);
            Console.WriteLine("Press enter to continue ....");
            Console.ReadLine();
            Console.Clear();
            sw.Reset();

            sw.Start();
            var parallelQuery = from t in
                                ParallelEnumerable.AsParallel(GetTypes())
                                select EmulateProcessing(t);

            sw.Stop();
            //foreach (string typeName in parallelQuery)
            //{
            //    PrintInfo(typeName);
            //}
            Console.WriteLine("---");
            Console.WriteLine("2Parallel LINQ query The results are being merged on a single thread");
            Console.WriteLine("Time elapsed:{0}", sw.Elapsed);
            Console.WriteLine("Press ENTER to continue ...");
            Console.ReadLine();
            Console.Clear();
            sw.Reset();

            //耗时最短
            sw.Start();
            parallelQuery = from t in GetTypes().AsParallel()
                            select EmulateProcessing(t);

            //var list = parallelQuery.ToList();
            sw.Stop();
            //parallelQuery.ForAll(PrintInfo);
            Console.WriteLine("----");
            Console.WriteLine("3Parallel LINQ query result being processed in parallel");
            Console.WriteLine("Time elapsed :{0}", sw.Elapsed);
            Console.WriteLine("Press ENTER to continue ..");
            Console.ReadLine();
            Console.Clear();
            sw.Reset();
            sw.Start();
            query = from t in GetTypes().AsParallel().AsSequential()
                    select EmulateProcessing(t);

            sw.Stop();
            //foreach (var typeName in query)
            //{
            //    PrintInfo(typeName);
            //}
            Console.WriteLine("----");
            Console.WriteLine("4Parallel LINQ query, transformed into sequential");
            Console.WriteLine("Time elapsedL:{0}", sw.Elapsed);
            Console.WriteLine("Press Enter to continue");
            Console.ReadLine();
            Console.Clear();
        }