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


C# Task<TResult>.ContinueWith方法代码示例

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


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

示例1: Main

//引入命名空间
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Timers = System.Timers;

public class Example
{
   static CancellationTokenSource ts;
   
   public static void Main(string[] args)
   {
      int upperBound = args.Length >= 1 ? Int32.Parse(args[0]) : 200;
      ts = new CancellationTokenSource();
      CancellationToken token = ts.Token;
      Timers.Timer timer = new Timers.Timer(3000);
      timer.Elapsed += TimedOutEvent;
      timer.AutoReset = false;
      timer.Enabled = true;

      var t1 = Task.Run(() => { // True = composite.
                                // False = prime.
                                bool[] values = new bool[upperBound + 1];
                                for (int ctr = 2; ctr <= (int) Math.Sqrt(upperBound); ctr++) {
                                   if (values[ctr] == false) {
                                      for (int product = ctr * ctr; product <= upperBound;
                                                                    product = product + ctr)
                                         values[product] = true;
                                   }
                                   token.ThrowIfCancellationRequested();
                                }
                                return values; }, token);

      var t2 = t1.ContinueWith( (antecedent) => { // Create a list of prime numbers.
                                                  var  primes = new List<int>();
                                                  token.ThrowIfCancellationRequested();
                                                  bool[] numbers = antecedent.Result;
                                                  string output = String.Empty;

                                                  for (int ctr = 1; ctr <= numbers.GetUpperBound(0); ctr++)
                                                     if (numbers[ctr] == false)
                                                        primes.Add(ctr);

                                                  // Create the output string.
                                                  for (int ctr = 0; ctr < primes.Count; ctr++) {
                                                     token.ThrowIfCancellationRequested();
                                                     output += primes[ctr].ToString("N0");
                                                     if (ctr < primes.Count - 1)
                                                        output += ",  ";
                                                     if ((ctr + 1) % 8 == 0)
                                                        output += Environment.NewLine;
                                                  }
                                                  //Display the result.
                                                  Console.WriteLine("Prime numbers from 1 to {0}:\n",
                                                                    upperBound);
                                                  Console.WriteLine(output);
                                                }, token);
      try {
         t2.Wait();
      }
      catch (AggregateException ae) {
         foreach (var e in ae.InnerExceptions) {
            if (e.GetType() == typeof(TaskCanceledException))
               Console.WriteLine("The operation was cancelled.");
            else
               Console.WriteLine("ELSE: {0}: {1}", e.GetType().Name, e.Message);
         }
      }
      finally {
         ts.Dispose();
      }
   }

   private static void TimedOutEvent(Object source, Timers.ElapsedEventArgs e)
   {
      ts.Cancel();
   }
}
// If cancellation is not requested, the example displays output like the following:
//       Prime numbers from 1 to 400:
//
//       1,  2,  3,  5,  7,  11,  13,  17,
//       19,  23,  29,  31,  37,  41,  43,  47,
//       53,  59,  61,  67,  71,  73,  79,  83,
//       89,  97,  101,  103,  107,  109,  113,  127,
//       131,  137,  139,  149,  151,  157,  163,  167,
//       173,  179,  181,  191,  193,  197,  199,  211,
//       223,  227,  229,  233,  239,  241,  251,  257,
//       263,  269,  271,  277,  281,  283,  293,  307,
//       311,  313,  317,  331,  337,  347,  349,  353,
//       359,  367,  373,  379,  383,  389,  397,  401
// If cancellation is requested, the example displays output like the following:
//       The operation was cancelled.
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:94,代码来源:Task.ContinueWith

示例2: Main

//引入命名空间
using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var cts = new CancellationTokenSource();
      var token = cts.Token;

      // Get an integer to generate a list of its exponents.
      var rnd = new Random();
      var number = rnd.Next(2, 21);
      
      var t = Task.Factory.StartNew( (value) => { int n = (int) value;
                                                  long[] values = new long[10];
                                                  for (int ctr = 1; ctr <= 10; ctr++)
                                                     values[ctr - 1] = (long) Math.Pow(n, ctr);
                                                     
                                                  return values;
                                                }, number);
      var continuation = t.ContinueWith( (antecedent, value) => { Console.WriteLine("Exponents of {0}:", value);
                                                                  for (int ctr = 0; ctr <= 9; ctr++)
                                                                     Console.WriteLine("   {0} {1} {2} = {3:N0}",
                                                                                       value, "\u02C6", ctr + 1,
                                                                                       antecedent.Result[ctr]);
                                                                  Console.WriteLine();
                                                                }, number);
      continuation.Wait();
      cts.Dispose();
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:34,代码来源:Task.ContinueWith

输出:

Exponents of 2:
2 ^ 1 = 2
2 ^ 2 = 4
2 ^ 3 = 8
2 ^ 4 = 16
2 ^ 5 = 32
2 ^ 6 = 64
2 ^ 7 = 128
2 ^ 8 = 256
2 ^ 9 = 512
2 ^ 10 = 1,024

示例3: Main

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

public class Example
{
   public static void Main(string[] args)
   {
      int upperBound = args.Length >= 1 ? Int32.Parse(args[0]) : 200;

      var t1 = Task.Run(() => { // True = composite.
                                // False = prime.
                                bool[] values = new bool[upperBound + 1];
                                for (int ctr = 2; ctr <= (int) Math.Sqrt(upperBound); ctr++) {
                                   if (values[ctr] == false) {
                                      for (int product = ctr * ctr; product <= upperBound;
                                                                    product = product + ctr)
                                         values[product] = true;
                                   }
                                }
                                return values; });
      var t2 = t1.ContinueWith( (antecedent) => { // Create a list of prime numbers.
                                                  var  primes = new List<int>();
                                                  bool[] numbers = antecedent.Result;
                                                  string output = String.Empty;

                                                  for (int ctr = 1; ctr <= numbers.GetUpperBound(0); ctr++)
                                                     if (numbers[ctr] == false)
                                                        primes.Add(ctr);

                                                  // Create the output string.
                                                  for (int ctr = 0; ctr < primes.Count; ctr++) {
                                                     output += primes[ctr].ToString("N0");
                                                     if (ctr < primes.Count - 1)
                                                        output += ",  ";
                                                     if ((ctr + 1) % 8 == 0)
                                                        output += Environment.NewLine;
                                                  }
                                                  //Display the result.
                                                  Console.WriteLine("Prime numbers from 1 to {0}:\n",
                                                                    upperBound);
                                                  Console.WriteLine(output);
                                                });
      try {
         t2.Wait();
      }
      catch (AggregateException ae) {
         foreach (var e in ae.InnerExceptions)
            Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message);
      }
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:54,代码来源:Task.ContinueWith

输出:

Prime numbers from 1 to 400:

1,  2,  3,  5,  7,  11,  13,  17,
19,  23,  29,  31,  37,  41,  43,  47,
53,  59,  61,  67,  71,  73,  79,  83,
89,  97,  101,  103,  107,  109,  113,  127,
131,  137,  139,  149,  151,  157,  163,  167,
173,  179,  181,  191,  193,  197,  199,  211,
223,  227,  229,  233,  239,  241,  251,  257,
263,  269,  271,  277,  281,  283,  293,  307,
311,  313,  317,  331,  337,  347,  349,  353,
359,  367,  373,  379,  383,  389,  397,  401

示例4: DoWork

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

// Demonstrates how to associate state with task continuations.
class ContinuationState
{
   // Simluates a lengthy operation and returns the time at which
   // the operation completed.
   public static DateTime DoWork()
   {
      // Simulate work by suspending the current thread 
      // for two seconds.
      Thread.Sleep(2000);

      // Return the current time.
      return DateTime.Now;
   }

   static void Main(string[] args)
   {
      // Start a root task that performs work.
      Task<DateTime> t = Task<DateTime>.Run(delegate { return DoWork(); });

      // Create a chain of continuation tasks, where each task is 
      // followed by another task that performs work.
      List<Task<DateTime>> continuations = new List<Task<DateTime>>();
      for (int i = 0; i < 5; i++)
      {
         // Provide the current time as the state of the continuation.
         t = t.ContinueWith(delegate { return DoWork(); }, DateTime.Now);
         continuations.Add(t);
      }

      // Wait for the last task in the chain to complete.
      t.Wait();

      // Print the creation time of each continuation (the state object)
      // and the completion time (the result of that task) to the console.
      foreach (var continuation in continuations)
      {
         DateTime start = (DateTime)continuation.AsyncState;
         DateTime end = continuation.Result;

         Console.WriteLine("Task was created at {0} and finished at {1}.",
            start.TimeOfDay, end.TimeOfDay);
      }
   }
}

/* Sample output:
Task was created at 10:56:21.1561762 and finished at 10:56:25.1672062.
Task was created at 10:56:21.1610677 and finished at 10:56:27.1707646.
Task was created at 10:56:21.1610677 and finished at 10:56:29.1743230.
Task was created at 10:56:21.1610677 and finished at 10:56:31.1779883.
Task was created at 10:56:21.1610677 and finished at 10:56:33.1837083.
*/
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:59,代码来源:Task.ContinueWith


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