What's dream?

.NET并行计算和并发7-Task异步

使用任务并行库执行异步任务 下面的示例演示如何通过调用 TaskFactory.StartNew 方法来创建并使用 Task 对象。

  1 using System;
  2 using System.Threading;
  3 using System.Threading.Tasks;
  4 
  5 class Example
  6 {
  7     static void Main()
  8     {
  9         Action<object> action = (object obj) =>
 10         {
 11             Console.WriteLine("Task={0}, obj={1}, Thread={2}",
 12             Task.CurrentId, obj,
 13             Thread.CurrentThread.ManagedThreadId);
 14         };
 15 
 16         // Create a task but do not start it.
 17         Task t1 = new Task(action, "alpha");
 18 
 19         // Construct a started task
 20         Task t2 = Task.Factory.StartNew(action, "beta");
 21         // Block the main thread to demonstate that t2 is executing
 22         t2.Wait();
 23 
 24         // Launch t1 
 25         t1.Start();
 26         Console.WriteLine("t1 has been launched. (Main Thread={0})",
 27                           Thread.CurrentThread.ManagedThreadId);
 28         // Wait for the task to finish.
 29         t1.Wait();
 30 
 31         // Construct a started task using Task.Run.
 32         String taskData = "delta";
 33         Task t3 = Task.Run(() =>
 34         {
 35             Console.WriteLine("Task={0}, obj={1}, Thread={2}",
 36                               Task.CurrentId, taskData,
 37                                Thread.CurrentThread.ManagedThreadId);
 38         });
 39         // Wait for the task to finish.
 40         t3.Wait();
 41 
 42         // Construct an unstarted task
 43         Task t4 = new Task(action, "gamma");
 44         // Run it synchronously
 45         t4.RunSynchronously();
 46         // Although the task was run synchronously, it is a good practice
 47         // to wait for it in the event exceptions were thrown by the task.
 48         t4.Wait();
 49     }
 50 }
 51 // The example displays output like the following:
 52 //       Task=1, obj=beta, Thread=3
 53 //       t1 has been launched. (Main Thread=1)
 54 //       Task=2, obj=alpha, Thread=4
 55 //       Task=3, obj=delta, Thread=3
 56 //       Task=4, obj=gamma, Thread=1
 57 
View Code

posted on 2017-08-18 17:29  kiss88  阅读(315)  评论(0)    收藏  举报