当前位置: 首页>>代码示例>>C#>>正文


C# IEnumerable.AsParallel方法代码示例

本文整理汇总了C#中IEnumerable.AsParallel方法的典型用法代码示例。如果您正苦于以下问题:C# IEnumerable.AsParallel方法的具体用法?C# IEnumerable.AsParallel怎么用?C# IEnumerable.AsParallel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IEnumerable的用法示例。


在下文中一共展示了IEnumerable.AsParallel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ChangeCreatingDateTimeForFiles

        /// <summary>
        /// Change time creating photo for all photofiles in folder
        /// </summary>
        /// <param name="pathToFiles">path to files</param>
        /// <param name="l_minutes">minutes for change (allow plus or minus value)</param>
        /// <returns>count changed files</returns>
        public int ChangeCreatingDateTimeForFiles(IEnumerable<string> pathToFiles, int minutes, out string errors)
        {
            StringBuilder errorFiles = new StringBuilder();
            errors = "";
            if (pathToFiles.Count() == 0)
                return 0;

            var countChangedFiles =
                pathToFiles.AsParallel()
                         .Where(filePath =>
                            {
                                string error;
                                var res =
                                     changeExifInformationInFile(filePath,
                                     createDirectoryForOutput(filePath), out error,
                                     (EXIFFileWorker photoExifInfo, out string errorInMethod) =>
                                     {
                                         errorInMethod = "";
                                         photoExifInfo.ChangeTime(minutes);
                                         return true;
                                     });
                                if (!res)
                                    errorFiles.AppendLine(error);
                                return res;
                            })
                          .Count();

            // return count changed files
            errors = errorFiles.ToString();
            return countChangedFiles;
        }
开发者ID:TyurinaMariya,项目名称:EXIFPhotoEditor,代码行数:37,代码来源:ChangeDataClass.cs

示例2: Execute

        public override IEnumerable<PvcStream> Execute(IEnumerable<PvcCore.PvcStream> inputStreams)
        {
            var outputStreams = new List<PvcStream>();
            foreach (var inputStream in inputStreams.AsParallel())
            {
                var browserifyBundle = PvcRuntimeNodeJs<PvcBrowserify>.Execute(
                    new
                    {
                        entryPoint = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(inputStream.StreamName))
                    },
                    @"
                        var browserify = require('browserify');

                        browserify(pvc.data.entryPoint)
                            .bundle(function (err, output) {
                                pvc.doneCallback(err, output);
                            })
                            .on('error', function (err) {
                                console.error(err);
                            });
                    "
                );

                outputStreams.Add(PvcUtil.StringToStream(browserifyBundle, inputStream.StreamName));
            }

            return outputStreams;
        }
开发者ID:pvcbuild,项目名称:pvc-browserify,代码行数:28,代码来源:PvcBrowserify.cs

示例3: OrderFiles

        public IEnumerable<FileInfo> OrderFiles(BundleContext context, IEnumerable<FileInfo> files)
        {
            var workingItems = files.AsParallel().Select(i => new _WorkingItem {
                Path = i.FullName,
                FileInfo = i,
                Dependencies = this._GetDependencies(i.FullName),
            });

            var fileDependencies = new Dictionary<string, _WorkingItem>(_DependencyNameComparer);
            foreach (var item in workingItems) {
                _WorkingItem duplicate;
                if (fileDependencies.TryGetValue(item.Path, out duplicate))
                    throw new ArgumentException(string.Format("During dependency resolution, a collision between '{0}' and '{1}' was detected. Files in a bundle must not collide with respect to the dependency name comparer.", Path.GetFileName(item.Path), Path.GetFileName(duplicate.Path)));

                fileDependencies.Add(item.Path, item);
            }

            foreach (var item in fileDependencies.Values) {
                foreach (var dependency in item.Dependencies) {
                    if (!fileDependencies.ContainsKey(dependency))
                        throw new ArgumentException(string.Format("Dependency '{0}' referenced by '{1}' could not found. Ensure the dependency is part of the bundle and its name can be detected by the dependency name comparer. If the dependency is not supposed to be in the bundle, add it to the list of excluded dependencies.", Path.GetFileName(dependency), Path.GetFileName(item.Path)));
                }
            }

            while (fileDependencies.Count > 0) {
                var result = fileDependencies.Values.FirstOrDefault(f => f.Dependencies.All(d => !fileDependencies.ContainsKey(d)));
                if (result == null)
                    throw new ArgumentException(string.Format("During dependency resolution, a cyclic dependency was detected among the remaining dependencies {0}.", string.Join(", ", fileDependencies.Select(d => "'" + Path.GetFileName(d.Value.Path) + "'"))));
                yield return result.FileInfo;
                fileDependencies.Remove(result.Path);
            }
        }
开发者ID:jyboudreau,项目名称:bundling,代码行数:32,代码来源:ScriptDependencyOrderer.cs

示例4: UpdateExifProperties

 public IEnumerable<SelectedImage> UpdateExifProperties(IEnumerable<SelectedImage> selectedImages)
 {
     if (selectedImages == null)
         return selectedImages;
     selectedImages.AsParallel().ForAll(selectedImage =>
     {
         try
         {
             var serverPath = _mediaFileSystemService.GetServerPath(selectedImage.FilePath);
             if (!File.Exists(serverPath))
                 return;
             var fileInfo = new FileInfo(serverPath);
             if (fileInfo.Extension.ToLower() == ".jpg")
             {
                 var reader = new ExifReader(serverPath);
                 selectedImage.Latitude = reader.GetLat();
                 selectedImage.Longtitude = reader.GetLon();
             }
         }
         catch (Exception e)
         {
         } 
     });
     return selectedImages;
 }
开发者ID:pavelvolek,项目名称:SYBA.ObalRoku,代码行数:25,代码来源:SelectedImageService.cs

示例5: FindReferences

		private IEnumerable<SharpTreeNode> FindReferences(IEnumerable<LoadedAssembly> assemblies, CancellationToken ct)
		{
			assemblies = assemblies.Where(asm => asm.AssemblyDefinition != null);

			// use parallelism only on the assembly level (avoid locks within Cecil)
			return assemblies.AsParallel().WithCancellation(ct).SelectMany((LoadedAssembly asm) => FindReferences(asm, ct));
		}
开发者ID:keremkusmezer,项目名称:ILSpy,代码行数:7,代码来源:AnalyzedMethodOverridesTreeNode.cs

示例6: RegisterTypeAsParallel

        /// <summary>
        ///		<para><see cref="IFrameworkContainer"/> 컨테이너에 등록할 개체를 Task Parallel Library 를 이용하여 병렬로 처리합니다.</para>
        ///		<para>단, 컨테이너에 개체를 등록할 때 CPU Process 의 개수를 이용하여 등록합니다.</para>
        ///		<para>단, 오버헤드가 높을 수 있는 작업이므로 <see cref="IFrameworkContainer"/> 의 내부적인 모든 작업을 병렬화 합니다.</para>
        ///		<para>단, 병렬 작업은 .NET Framework 4.0 빌드에서만 동작합니다.</para>
        /// </summary>
        /// <param name="container"></param>
        /// <param name="action"></param>
        public static void RegisterTypeAsParallel(this IFrameworkContainer container, IEnumerable<Action> action)
        {
            ConcurrentQueue<Exception> exceptions = null;
            try
            {
                exceptions = new ConcurrentQueue<Exception>();

                try
                {
                    action.AsParallel()
                            .WithDegreeOfParallelism(Environment.ProcessorCount)
                            .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
                            .ForAll( o => o());

                }
                catch (Exception ex)
                {
                    exceptions.Enqueue(ex);
                }
            }
            catch (Exception)
            {
                if( exceptions != null )
                    exceptions.ToList().ForEach( o => Trace.WriteLine( o.Message ));

                throw;
            }
        }
开发者ID:powerumc,项目名称:UmcCore,代码行数:36,代码来源:FrameworkContainerExtensions.cs

示例7: FindRepetitions

        /// <summary>
        /// Durchsucht die nach länge gruppierte Liste von Teilzeichenolgen nach Wiederholungen.
        /// </summary>
        /// <param name="substringsGroupedByLength">Die nach länge gruppierte Liste von Teilzeichenfolgen.</param>
        /// <param name="cores">Die Anzahl der zu benutzenden CPU-Kerne. 0 verwendet 
        /// alle zur Verfügung stehenden.</param>
        /// <returns>Eine Liste aller Teilzeichenfolgen in <paramref name="substringsGroupedByLength"/>,
        /// wobei wiederholungen in einem Element zusammen gefasst wurden.</returns>
        public static IEnumerable<Occurence> FindRepetitions(IEnumerable<IEnumerable<Substring>> substringsGroupedByLength, int cores = 0)
        {
            var enu = substringsGroupedByLength.AsParallel();
            if (cores > 0)
            {
                enu = enu.WithDegreeOfParallelism(cores);
            }
            foreach (var group in enu)
            {
                var items = group.ToArray();
                for (var index1 = 0; index1 < items.Length; ++index1)
                {
                    if (items[index1] == null) { continue; }
                    var occ = new Occurence(items[index1].Text);
                    occ.Indices.Add(items[index1].Index);
                    for (var index2 = index1 + 1; index2 < items.Length; ++index2)
                    {
                        if (items[index2] == null || items[index1].Text != items[index2].Text) { continue; }

                        occ.Indices.Add(items[index2].Index);
                        items[index2] = null;
                    }
                    yield return occ;
                }
            }
        }
开发者ID:Koopakiller,项目名称:School,代码行数:34,代码来源:OccurenceFinder.cs

示例8: UseCancellation

        private static void UseCancellation(IEnumerable<int> data)
        {
            WriteLine(nameof(UseCancellation));
            var cts = new CancellationTokenSource();

            Task.Run(() =>
            {
                try
                {
                    var res = (from x in data.AsParallel().WithCancellation(cts.Token)
                               where Math.Log(x) < 4
                               select x).Average();

                    WriteLine($"query finished, sum: {res}");
                }
                catch (OperationCanceledException ex)
                {
                    WriteLine(ex.Message);
                }
            });

            WriteLine("query started");
            Write("cancel? ");
            string input = ReadLine();
            if (input.ToLower().Equals("y"))
            {
                cts.Cancel();
            }

            WriteLine();
        }
开发者ID:ProfessionalCSharp,项目名称:ProfessionalCSharp6,代码行数:31,代码来源:Program.cs

示例9: sameUnitPriceOriginalPLINQ

 public static void sameUnitPriceOriginalPLINQ(IEnumerable<Product> products)
 {
     TestingEnvironment.BenchmarkQuery(() => products.AsParallel().Where(p => categoriesToAudit.Contains(p.category)).SelectMany(p => products.Where(p2 => !p2.category.Equals(p.category) && p2.unitPrice == p.unitPrice).Select(p2 => p.productName + " and " + p2.productName)),
                ref products,
                "Original Same unitPrice Lambda Expession with PLINQ",
                "products.AsParallel().Where(p => categoriesToAudit.Contains(p.category)).SelectMany(p => products.Where(p2 => !p2.category.Equals(p.category) && p2.unitPrice == p.unitPrice).Select(p2 => p.productName + \" and \" + p2.productName))"
                );
 }
开发者ID:radamus,项目名称:OptimizableLINQ,代码行数:8,代码来源:TestVolatileIndexing.cs

示例10: Encrypt

          Encrypt(IEnumerable<string> data)
        {

            OrderedParallelQuery<string> parallelGroups =
            data.AsParallel().OrderBy(item => item);

            // Show the total count of items still
            // matches the original count
            System.Diagnostics.Trace.Assert(
                data.Count() == parallelGroups.Sum(
                    item => item.Count()));
            // ...


            return data.AsParallel().Select(
                item => Encrypt(item)).ToList();
        }
开发者ID:troubleminds,项目名称:TIP,代码行数:17,代码来源:Listing18.31.ParallelLinqStandardQueryOperators.cs

示例11: ImportAccounts

 public static void ImportAccounts(IEnumerable<string> importAccounts)
 {
     importAccounts
         .AsParallel()
         .ForAll(account => {
             var completionTask = ImportAccountAsync(account);
         });
 }
开发者ID:CedarLogic,项目名称:Dash,代码行数:8,代码来源:AccountManager.cs

示例12: FunctionalParallelMerge

 public static Company FunctionalParallelMerge(Company bigCompany, IEnumerable<Company> smallCompanies)
 {
     return smallCompanies
         .AsParallel()
         .Aggregate(CreateShell,
             (shell, smallCompany) => shell.Merge(smallCompany),
             (shell1, shell2) => shell1.Merge(shell2),
             bigCompany.Merge);
 }
开发者ID:cuipengfei,项目名称:Spikes,代码行数:9,代码来源:FunctionalParallelMerger.cs

示例13: UpdaterClientEventArgs

 public UpdaterClientEventArgs(IEnumerable<AvailableUpdate> items)
     : this("Finished checking for Updates")
 {
     items.AsParallel().ForAll(item =>
     {
         this.items.Add(item.Date, item);
     });
     this.Completed = true;
 }
开发者ID:priestofpsi,项目名称:Hide-My-Window,代码行数:9,代码来源:UpdaterClientEventArgs.cs

示例14: Fastest

        /// <summary>
        /// Resolves the fastest Uri in a collection.
        /// </summary>
        /// <param name="uris">Enumerable collection of Uris.</param>
        /// <returns>Fastest Uri in the collection.</returns>
        public Uri Fastest(IEnumerable<Uri> uris)
        {
            if (uris == null)
                throw new ArgumentNullException("uris");

            return uris.AsParallel()
                .OrderBy(_ => _score.Score(_.DnsSafeHost))
                .First();
        }
开发者ID:rmuch,项目名称:FastestMirror,代码行数:14,代码来源:FastestMirrorResolver.cs

示例15: LinqQuery

 private static void LinqQuery(IEnumerable<int> data)
 {
     WriteLine(nameof(LinqQuery));
     var res = (from x in data.AsParallel()
                where Math.Log(x) < 4
                select x).Average();
     WriteLine($"result from {nameof(LinqQuery)}: {res}");
     WriteLine();
 }
开发者ID:ProfessionalCSharp,项目名称:ProfessionalCSharp6,代码行数:9,代码来源:Program.cs


注:本文中的IEnumerable.AsParallel方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。