本文整理汇总了C#中System.Threading.Tasks.Parallel.ForEach方法的典型用法代码示例。如果您正苦于以下问题:C# Parallel.ForEach方法的具体用法?C# Parallel.ForEach怎么用?C# Parallel.ForEach使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.Tasks.Parallel
的用法示例。
在下文中一共展示了Parallel.ForEach方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class ForEachWithThreadLocal
{
// Demonstrated features:
// Parallel.ForEach()
// Thread-local state
// Expected results:
// This example sums up the elements of an int[] in parallel.
// Each thread maintains a local sum. When a thread is initialized, that local sum is set to 0.
// On every iteration the current element is added to the local sum.
// When a thread is done, it safely adds its local sum to the global sum.
// After the loop is complete, the global sum is printed out.
// Documentation:
// http://msdn.microsoft.com/library/dd990270(VS.100).aspx
static void Main()
{
// The sum of these elements is 40.
int[] input = { 4, 1, 6, 2, 9, 5, 10, 3 };
int sum = 0;
try
{
Parallel.ForEach(
input, // source collection
() => 0, // thread local initializer
(n, loopState, localSum) => // body
{
localSum += n;
Console.WriteLine("Thread={0}, n={1}, localSum={2}", Thread.CurrentThread.ManagedThreadId, n, localSum);
return localSum;
},
(localSum) => Interlocked.Add(ref sum, localSum) // thread local aggregator
);
Console.WriteLine("\nSum={0}", sum);
}
// No exception is expected in this example, but if one is still thrown from a task,
// it will be wrapped in AggregateException and propagated to the main thread.
catch (AggregateException e)
{
Console.WriteLine("Parallel.ForEach has thrown an exception. THIS WAS NOT EXPECTED.\n{0}", e);
}
}
}
示例2: Main
//引入命名空间
using System;
using System.IO;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
Task<String> task = ReadCharacters(@".\CallOfTheWild.txt");
String text = task.Result;
int nVowels = 0;
int nNonWhiteSpace = 0;
Object obj = new Object();
ParallelLoopResult result = Parallel.ForEach(text,
(ch) => {
Char uCh = Char.ToUpper(ch);
if ("AEIOUY".IndexOf(uCh) >= 0) {
lock (obj) {
nVowels++;
}
}
if (! Char.IsWhiteSpace(uCh)) {
lock (obj) {
nNonWhiteSpace++;
}
}
} );
Console.WriteLine("Total characters: {0,10:N0}", text.Length);
Console.WriteLine("Total vowels: {0,10:N0}", nVowels);
Console.WriteLine("Total non-white-space: {0,10:N0}", nNonWhiteSpace);
}
private static async Task<String> ReadCharacters(String fn)
{
String text;
using (StreamReader sr = new StreamReader(fn)) {
text = await sr.ReadToEndAsync();
}
return text;
}
}
输出:
Total characters: 198,548 Total vowels: 58,421 Total non-white-space: 159,461
示例3: Main
//引入命名空间
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
class RangePartitionerDemo
{
static void Main()
{
Stopwatch sw = null;
long sum = 0;
long SUMTOP = 10000000;
// Try sequential for
sw = Stopwatch.StartNew();
for (long i = 0; i < SUMTOP; i++) sum += i;
sw.Stop();
Console.WriteLine("sequential for result = {0}, time = {1} ms", sum, sw.ElapsedMilliseconds);
// Try parallel for -- this is slow!
//sum = 0;
//sw = Stopwatch.StartNew();
//Parallel.For(0L, SUMTOP, (item) => Interlocked.Add(ref sum, item));
//sw.Stop();
//Console.WriteLine("parallel for result = {0}, time = {1} ms", sum, sw.ElapsedMilliseconds);
// Try parallel for with locals
sum = 0;
sw = Stopwatch.StartNew();
Parallel.For(0L, SUMTOP, () => 0L, (item, state, prevLocal) => prevLocal + item, local => Interlocked.Add(ref sum, local));
sw.Stop();
Console.WriteLine("parallel for w/locals result = {0}, time = {1} ms", sum, sw.ElapsedMilliseconds);
// Try range partitioner
sum = 0;
sw = Stopwatch.StartNew();
Parallel.ForEach(Partitioner.Create(0L, SUMTOP), (range) =>
{
long local = 0;
for (long i = range.Item1; i < range.Item2; i++) local += i;
Interlocked.Add(ref sum, local);
});
sw.Stop();
Console.WriteLine("range partitioner result = {0}, time = {1} ms", sum, sw.ElapsedMilliseconds);
}
}