當前位置: 首頁>>代碼示例>>C#>>正文


C# Parallel.ForEach方法代碼示例

本文整理匯總了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);
        }
    }
}
開發者ID:.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:51,代碼來源:Parallel.ForEach

示例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;
   }
}
開發者ID:.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:44,代碼來源:Parallel.ForEach

輸出:

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);
        }
}
開發者ID:.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:49,代碼來源:Parallel.ForEach


注:本文中的System.Threading.Tasks.Parallel.ForEach方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。