本文整理汇总了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;
}
示例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;
}
示例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);
}
}
示例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;
}
示例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));
}
示例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;
}
}
示例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;
}
}
}
示例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();
}
示例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))"
);
}
示例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();
}
示例11: ImportAccounts
public static void ImportAccounts(IEnumerable<string> importAccounts)
{
importAccounts
.AsParallel()
.ForAll(account => {
var completionTask = ImportAccountAsync(account);
});
}
示例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);
}
示例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;
}
示例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();
}
示例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();
}