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


C# TaskFactory.StartNew方法代碼示例

本文整理匯總了C#中System.Threading.Tasks.TaskFactory.StartNew方法的典型用法代碼示例。如果您正苦於以下問題:C# TaskFactory.StartNew方法的具體用法?C# TaskFactory.StartNew怎麽用?C# TaskFactory.StartNew使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在System.Threading.Tasks.TaskFactory的用法示例。


在下文中一共展示了TaskFactory.StartNew方法的6個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: Main

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

public class Example
{
   public static void Main()
   {
      CancellationTokenSource cts = new CancellationTokenSource();
      CancellationToken token = cts.Token;
      var tasks = new List<Task>();
      Random rnd = new Random();
      Object lockObj = new Object();
      String[] words6 = { "reason", "editor", "rioter", "rental",
                          "senior", "regain", "ordain", "rained" };

      foreach (var word6 in words6)
         tasks.Add(Task.Factory.StartNew( (word) => { Char[] chars = word.ToString().ToCharArray();
                                                      double[] order = new double[chars.Length];
                                                      token.ThrowIfCancellationRequested();
                                                      bool wasZero = false;
                                                      lock (lockObj) {
                                                         for (int ctr = 0; ctr < order.Length; ctr++) {
                                                             order[ctr] = rnd.NextDouble();
                                                             if (order[ctr] == 0) {
                                                                if (! wasZero) {
                                                                   wasZero = true;
                                                                }
                                                                else {
                                                                   cts.Cancel();
                                                                }
                                                             }
                                                         }
                                                      }
                                                      token.ThrowIfCancellationRequested();
                                                      Array.Sort(order, chars);
                                                      Console.WriteLine("{0} --> {1}", word,
                                                                        new String(chars));
                                                    }, word6, token));

      try {
         Task.WaitAll(tasks.ToArray());
      }
      catch (AggregateException e) {
         foreach (var ie in e.InnerExceptions) {
            if (ie is OperationCanceledException) {
               Console.WriteLine("The word scrambling operation has been cancelled.");
               break;
            }
            else {
               Console.WriteLine(ie.GetType().Name + ": " + ie.Message);
            }
         }
      }
      finally {
         cts.Dispose();
      }
   }
}
開發者ID:.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:61,代碼來源:TaskFactory.StartNew

輸出:

regain --> irnaeg
ordain --> rioadn
reason --> soearn
rained --> rinade
rioter --> itrore
senior --> norise
rental --> atnerl
editor --> oteird

示例2: Main

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

public class Example
{
   public static void Main()
   {
      var tokenSource = new CancellationTokenSource();
      var token = tokenSource.Token;
      var files = new List<Tuple<string, string, long, DateTime>>();

      var t = Task.Factory.StartNew( () => { string dir = "C:\\Windows\\System32\\";
                                object obj = new Object();
                                if (Directory.Exists(dir)) {
                                   Parallel.ForEach(Directory.GetFiles(dir),
                                   f => {
                                           if (token.IsCancellationRequested)
                                              token.ThrowIfCancellationRequested();
                                           var fi = new FileInfo(f);
                                           lock(obj) {
                                              files.Add(Tuple.Create(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc));          
                                           }
                                      });
                                 }
                              }
                        , token);
      tokenSource.Cancel();
      try {
         t.Wait(); 
         Console.WriteLine("Retrieved information for {0} files.", files.Count);
      }
      catch (AggregateException e) {
         Console.WriteLine("Exception messages:");
         foreach (var ie in e.InnerExceptions)
            Console.WriteLine("   {0}: {1}", ie.GetType().Name, ie.Message);

         Console.WriteLine("\nTask status: {0}", t.Status);       
      }
      finally {
         tokenSource.Dispose();
      }
   }
}
開發者ID:.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:47,代碼來源:TaskFactory.StartNew

輸出:

Exception messages:
TaskCanceledException: A task was canceled.

Task status: Canceled

示例3: Main

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

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      List<Task> tasks  = new List<Task>();
      // Execute the task 10 times.
      for (int ctr = 1; ctr <= 9; ctr++) {
         tasks.Add(Task.Factory.StartNew( () => {
                                            int utf32 = 0;
                                            lock(rnd) {
                                               // Get UTF32 value.
                                               utf32 = rnd.Next(0, 0xE01F0);
                                            }
                                            // Convert it to a UTF16-encoded character.
                                            string utf16 = Char.ConvertFromUtf32(utf32);
                                            // Display information about the character.
                                            Console.WriteLine("0x{0:X8} --> '{1,2}' ({2})", 
                                                              utf32, utf16, ShowHex(utf16));
                                         }));                           
      }
      Task.WaitAll(tasks.ToArray()); 
   }

   private static string ShowHex(string value)
   {
      string hexString = null;
      // Handle only non-control characters.
      if (! Char.IsControl(value, 0)) {
         foreach (var ch in value)
            hexString += String.Format("0x{0} ", Convert.ToUInt16(ch));
      }   
      return hexString.Trim();
   }
}
開發者ID:.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:40,代碼來源:TaskFactory.StartNew

輸出:

0x00097103 --> '򗄃' (0x55836 0x56579)
0x000A98A1 --> '򩢡' (0x55910 0x56481)
0x00050002 --> '񐀂' (0x55552 0x56322)
0x0000FEF1 --> 'ﻱ' (0x65265)
0x0008BC0A --> '򋰊' (0x55791 0x56330)
0x000860EA --> '򆃪' (0x55768 0x56554)
0x0009AC5A --> '򚱚' (0x55851 0x56410)
0x00053320 --> '񓌠' (0x55564 0x57120)
0x000874EF --> '򇓯' (0x55773 0x56559)

示例4: Main

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

public class Example
{
   public static void Main()
   {
      var tasks = new List<Task>();
      Random rnd = new Random();
      Object lockObj = new Object();
      String[] words6 = { "reason", "editor", "rioter", "rental",
                          "senior", "regain", "ordain", "rained" };

      foreach (var word6 in words6)
         tasks.Add(Task.Factory.StartNew( (word) => { Char[] chars = word.ToString().ToCharArray();
                                                      double[] order = new double[chars.Length];
                                                      lock (lockObj) {
                                                         for (int ctr = 0; ctr < order.Length; ctr++)
                                                             order[ctr] = rnd.NextDouble();
                                                      }
                                                      Array.Sort(order, chars);
                                                      Console.WriteLine("{0} --> {1}", word,
                                                                        new String(chars));
                                                    }, word6));

      Task.WaitAll(tasks.ToArray());
   }
}
開發者ID:.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:30,代碼來源:TaskFactory.StartNew

輸出:

regain --> irnaeg
ordain --> rioadn
reason --> soearn
rained --> rinade
rioter --> itrore
senior --> norise
rental --> atnerl
editor --> oteird

示例5: Main

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

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      Task<int>[] tasks = new Task<int>[2];
      Object obj = new Object();
      
      while (true) {
         for (int ctr = 0; ctr <= 1; ctr++)
            tasks[ctr] = Task.Factory.StartNew(() => { int i = 0;
                                                       lock(obj) {
                                                          i = rnd.Next(101);
                                                       }
                                                       return i; });

         Task.WaitAll(tasks);
         int n1 = tasks[0].Result;
         int n2 = tasks[1].Result;
         int result = n1 + n2;
         bool validInput = false;
         while (! validInput) {
            ShowMessage(n1, n2);
            string userInput = Console.ReadLine();
            // Process user input.
            if (userInput.Trim().ToUpper() == "X") return;
            int answer;
            validInput = Int32.TryParse(userInput, out answer);
            if (! validInput)
               Console.WriteLine("Invalid input. Try again, but enter only numbers. ");
            else if (answer == result)
               Console.WriteLine("Correct!");
            else
               Console.WriteLine("Incorrect. The correct answer is {0}.", result);
         }
      }
   }

   private static void ShowMessage(int n1, int n2)
   {
      Console.WriteLine("\nEnter 'x' to exit...");
      Console.Write("{0} + {1} = ", n1, n2);
   }
}
開發者ID:.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:48,代碼來源:TaskFactory.StartNew

輸出:

Enter 'x' to exit...
15 + 11 = 26
Correct!

Enter 'x' to exit...
75 + 33 = adc
Invalid input. Try again, but enter only numbers.

Enter 'x' to exit...
75 + 33 = 108
Correct!

Enter 'x' to exit...
67 + 55 = 133
Incorrect. The correct answer is 122.

Enter 'x' to exit...
92 + 51 = 133
Incorrect. The correct answer is 143.

Enter 'x' to exit...
81 + 65 = x

示例6: Main

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

public class Example
{
   public static void Main()
   {
      var rnd = new Random();
      var tasks = new List<Task<BigInteger[]>>();
      var source = new CancellationTokenSource();
      var token = source.Token;
      for (int ctr = 0; ctr <= 1; ctr++) {
         int start = ctr;
         tasks.Add(Task.Run( () => { BigInteger[] sequence = new BigInteger[100];
                                     sequence[0] = start;
                                     sequence[1] = 1;
                                     for (int index = 2; index <= sequence.GetUpperBound(0); index++) {
                                        token.ThrowIfCancellationRequested();
                                        sequence[index] = sequence[index - 1] + sequence[index - 2];
                                     }
                                     return sequence;
                                   }, token));
      }
      if (rnd.Next(0, 2) == 1)
         source.Cancel();
      try {
         Task.WaitAll(tasks.ToArray());
         foreach (var t in tasks)
            Console.WriteLine("{0}, {1}...{2:N0}", t.Result[0], t.Result[1],
                              t.Result[99]);
      }
      catch (AggregateException e) {
         foreach (var ex in e.InnerExceptions)
            Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message);
      }
   }
}
開發者ID:.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:41,代碼來源:TaskFactory.StartNew

輸出:

0, 1...218,922,995,834,555,169,026
1, 1...354,224,848,179,261,915,075
or the following output:
TaskCanceledException: A task was canceled.
TaskCanceledException: A task was canceled.


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