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


C# TaskFactory.ContinueWhenAll方法代码示例

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


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

示例1: Main

//引入命名空间
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string[] filenames = { "chapter1.txt", "chapter2.txt", 
                             "chapter3.txt", "chapter4.txt",
                             "chapter5.txt" };
      string pattern = @"\b\w+\b";
      var tasks = new List<Task>();  
      int totalWords = 0;
        
      // Determine the number of words in each file.
      foreach (var filename in filenames) 
         tasks.Add( Task.Factory.StartNew( fn => { if (! File.Exists(fn.ToString()))
                                                      throw new FileNotFoundException("{0} does not exist.", filename);

                                                   StreamReader sr = new StreamReader(fn.ToString());
                                                   String content = sr.ReadToEnd();
                                                   sr.Close();
                                                   int words = Regex.Matches(content, pattern).Count;
                                                   Interlocked.Add(ref totalWords, words); 
                                                   Console.WriteLine("{0,-25} {1,6:N0} words", fn, words); }, 
                                           filename));

      var finalTask = Task.Factory.ContinueWhenAll(tasks.ToArray(), wordCountTasks => {
                                                    int nSuccessfulTasks = 0;
                                                    int nFailed = 0;
                                                    int nFileNotFound = 0;
                                                    foreach (var t in wordCountTasks) {
                                                       if (t.Status == TaskStatus.RanToCompletion) 
                                                          nSuccessfulTasks++;
                                                       
                                                       if (t.Status == TaskStatus.Faulted) {
                                                          nFailed++;  
                                                          t.Exception.Handle( (e) => { 
                                                             if (e is FileNotFoundException)
                                                                nFileNotFound++;
                                                             return true;   
                                                          });
                                                       } 
                                                    }   
                                                    Console.WriteLine("\n{0,-25} {1,6} total words\n", 
                                                                      String.Format("{0} files", nSuccessfulTasks), 
                                                                      totalWords); 
                                                    if (nFailed > 0) {
                                                       Console.WriteLine("{0} tasks failed for the following reasons:", nFailed);
                                                       Console.WriteLine("   File not found:    {0}", nFileNotFound);
                                                       if (nFailed != nFileNotFound)
                                                          Console.WriteLine("   Other:          {0}", nFailed - nFileNotFound);
                                                    } 
                                                    });  
      finalTask.Wait();                                                                  
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:62,代码来源:TaskFactory.ContinueWhenAll

输出:

chapter2.txt               1,585 words
chapter1.txt               4,012 words
chapter5.txt               4,660 words
chapter3.txt               7,481 words

4 files                    17738 total words

1 tasks failed for the following reasons:
File not found:    1

示例2: Main

//引入命名空间
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string[] filenames = { "chapter1.txt", "chapter2.txt", 
                             "chapter3.txt", "chapter4.txt",
                             "chapter5.txt" };
      string pattern = @"\b\w+\b";
      var tasks = new List<Task>();  
      CancellationTokenSource source = new CancellationTokenSource();
      CancellationToken token = source.Token;
      int totalWords = 0;
        
      // Determine the number of words in each file.
      foreach (var filename in filenames)
         tasks.Add( Task.Factory.StartNew( fn => { token.ThrowIfCancellationRequested(); 

                                                   if (! File.Exists(fn.ToString())) {
                                                      source.Cancel();
                                                      token.ThrowIfCancellationRequested();
                                                   }
                                                   
                                                   StreamReader sr = new StreamReader(fn.ToString());
                                                   String content = sr.ReadToEnd();
                                                   sr.Close();
                                                   int words = Regex.Matches(content, pattern).Count;
                                                   Interlocked.Add(ref totalWords, words); 
                                                   Console.WriteLine("{0,-25} {1,6:N0} words", fn, words); }, 
                                           filename, token));

      var finalTask = Task.Factory.ContinueWhenAll(tasks.ToArray(), wordCountTasks => {
                                                    if (! token.IsCancellationRequested) 
                                                       Console.WriteLine("\n{0,-25} {1,6} total words\n", 
                                                                         String.Format("{0} files", wordCountTasks.Length), 
                                                                         totalWords); 
                                                   }, token); 
      try {                                                   
         finalTask.Wait();
      }
      catch (AggregateException ae) {
         foreach (Exception inner in ae.InnerExceptions)
            if (inner is TaskCanceledException)
               Console.WriteLine("\nFailure to determine total word count: a task was cancelled.");
            else
               Console.WriteLine("\nFailure caused by {0}", inner.GetType().Name);      
      }
      finally {
         source.Dispose();
      }
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:59,代码来源:TaskFactory.ContinueWhenAll

输出:

chapter2.txt               1,585 words
chapter1.txt               4,012 words

Failure to determine total word count: a task was cancelled.


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