当前位置: 首页>>代码示例>>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;未经允许,请勿转载。