.NET並行計算和並發7-Task非同步

來源:互聯網
上載者:User

標籤:ring   new   如何   view   task   star   action   非同步任務   dem   

使用工作平行程式庫執行非同步任務 下面的樣本示範如何通過調用 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

.NET並行計算和並發7-Task非同步

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.