class Program { static void Main(string[] args) { Task t = new Task(DoA); t.Start(); Console.ReadKey(); } static void DoA() { for (int i = 0; i < 100; i++) { Console.WriteLine("i={0}\n", i); } } }
2)透過Run,直接運行,接受參數一個Action,回傳物件是一個Task
static void Main(string[] args) { Task.Run(() => { for (int i = 0; i < 50; i++) { Console.WriteLine("i={0}",i); } }); Console.ReadKey(); }
3)帶回傳參數的執行緒
Task<int> task = Task.Run<int>(() => { int sum = 0; for (int i = 0; i < 50; i++) { sum += 1; } return sum; }); int result = task.Result; Console.WriteLine("运算结果是:{0}",result);//输出50 Console.ReadKey();
4)透過Task.Factory
Task t = Task.Factory.StartNew(() => { for (int i = 0; i < 10; i++) { Console.WriteLine("i={0}", i); } });
以上是Task用法之啟動方法實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!