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


C# Task構造函數代碼示例

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


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

示例1: Main

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

public class Example
{
   public static async Task Main()
   {
      var list = new ConcurrentBag<string>();
      string[] dirNames = { ".", ".." };
      List<Task> tasks = new List<Task>();
      foreach (var dirName in dirNames) {
         Task t = new Task( () => { foreach(var path in Directory.GetFiles(dirName))
                                    list.Add(path); }  );
         tasks.Add(t);
         t.Start();
      }
      await Task.WhenAll(tasks.ToArray());
      foreach (Task t in tasks)
         Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status);
         
      Console.WriteLine("Number of files read: {0}", list.Count);
   }
}
開發者ID:.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:27,代碼來源:Task

輸出:

Task 1 Status: RanToCompletion
Task 2 Status: RanToCompletion
Number of files read: 23

示例2: Main

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

public class Example
{
   public static void Main()
   {
      var list = new ConcurrentBag<string>();
      string[] dirNames = { ".", ".." };
      List<Task> tasks = new List<Task>();
      foreach (var dirName in dirNames) {
         Task t = Task.Run( () => { foreach(var path in Directory.GetFiles(dirName)) 
                                       list.Add(path); }  );
         tasks.Add(t);
      }
      Task.WaitAll(tasks.ToArray());
      foreach (Task t in tasks)
         Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status);
         
      Console.WriteLine("Number of files read: {0}", list.Count);
   }
}
開發者ID:.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:26,代碼來源:Task

輸出:

Task 1 Status: RanToCompletion
Task 2 Status: RanToCompletion
Number of files read: 23

示例3: Main

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

public class Example
{
   public static async Task Main()
   {
      var tokenSource = new CancellationTokenSource();
      var token = tokenSource.Token;
      var files = new List<Tuple<string, string, long, DateTime>>();
      
      var t = new Task(() => { 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);
      t.Start();
      tokenSource.Cancel();
      try {
         await t; 
         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,代碼來源:Task

輸出:

Exception messages:
TaskCanceledException: A task was canceled.

Task status: Canceled

示例4: Main

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

public class Example
{
   public static async Task 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) {
         Task t = new Task( (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);
         t.Start();
         tasks.Add(t);
      }
      await Task.WhenAll(tasks.ToArray());
   }
}
開發者ID:.NET開發者,項目名稱:System.Threading.Tasks,代碼行數:32,代碼來源:Task

輸出:

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


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