首页 / C#开发 / 正文

C#多任务并行执行(Parallel.Invoke)

51271 发布于: 2014-02-20 读完约需10分钟

C#的Parallel.Invoke是多任务并行执行的一个不错选择,代码简洁,以下是微软的官方示例

namespace ParallelTasks
{
  using System;
  using System.IO;
  using System.Linq;
  using System.Text;
  using System.Threading;
  using System.Threading.Tasks;
  using System.Net;

  class ParallelInvoke
  {
    static void Main()
    {
      // Retrieve Darwin's "Origin of the Species" from Gutenberg.org.
      string[] words = CreateWordArray(@"http://www.gutenberg.org/cache/epub/2009/pg2009.txt");

      #region ParallelTasks
      // Perform three tasks in parallel on the source array
      Parallel.Invoke(() =>
      {
        Console.WriteLine("Begin first task...");
        GetLongestWord(words);
      },  // close first Action

                       () =>
                       {
                         Console.WriteLine("Begin second task...");
                         GetMostCommonWords(words);
                       }, //close second Action

                       () =>
                       {
                         Console.WriteLine("Begin third task...");
                         GetCountForWord(words, "species");
                       } //close third Action
                   ); //close parallel.invoke

      Console.WriteLine("Returned from Parallel.Invoke");
      #endregion

      Console.WriteLine("Press any key to exit");
      Console.ReadKey();
    }

    #region HelperMethods
    private static void GetCountForWord(string[] words, string term)
    {
      var findWord = from word in words
                     where word.ToUpper().Contains(term.ToUpper())
                     select word;

      Console.WriteLine(@"Task 3 -- The word ""{0}"" occurs {1} times.",
          term, findWord.Count());
    }

    private static void GetMostCommonWords(string[] words)
    {
      var frequencyOrder = from word in words
                           where word.Length > 6
                           group word by word into g
                           orderby g.Count() descending
                           select g.Key;

      var commonWords = frequencyOrder.Take(10);

      StringBuilder sb = new StringBuilder();
      sb.AppendLine("Task 2 -- The most common words are:");
      foreach (var v in commonWords)
      {
        sb.AppendLine("  " + v);
      }
      Console.WriteLine(sb.ToString());
    }

    private static string GetLongestWord(string[] words)
    {
      var longestWord = (from w in words
                         orderby w.Length descending
                         select w).First();

      Console.WriteLine("Task 1 -- The longest word is {0}", longestWord);
      return longestWord;
    }

    // An http request performed synchronously for simplicity. 
    static string[] CreateWordArray(string uri)
    {
      Console.WriteLine("Retrieving from {0}", uri);

      // Download a web page the easy way. 
      string s = new WebClient().DownloadString(uri);

      // Separate string into an array of words, removing some common punctuation. 
      return s.Split(
          new char[] { ' ', 'u000A', ',', '.', ';', ':', '-', '_', '/' },
          StringSplitOptions.RemoveEmptyEntries);
    }
    #endregion
  }
}

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: C#正则表达式判断一个字符串中是否包含某个字词

下一篇: c# Task多线程并行任务中等待所有线程都执行完成

本文永久链接码友网 » C#多任务并行执行(Parallel.Invoke)

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册