任务提供两个主要好处:
-
系统资源的使用效率更高,可伸缩性更好。
这会使任务相对轻量,你可以创建很多任务以启用细化并行。
-
对于线程或工作项,可以使用更多的编程控件。
任务和围绕它们生成的框架提供了一组丰富的 API,这些 API 支持等待、取消、继续、可靠的异常处理、详细状态、自定义计划等功能。
出于这两个原因,在 .NET Framework 中,TPL 是用于编写多线程、异步和并行代码的首选 API。
using System; using System.Threading; using System.Threading.Tasks; public class Example { public static void Main() { Thread.CurrentThread.Name = "Main"; // Create a task and supply a user delegate by using a lambda expression. Task taskA = new Task( () => Console.WriteLine("Hello from taskA.")); // Start the task. taskA.Start(); // Output a message from the calling thread. Console.WriteLine("Hello from thread '{0}'.", Thread.CurrentThread.Name); taskA.Wait(); } } // The example displays the following output: // Hello from thread 'Main'. // Hello from taskA.
Run 方法创建并启动任务。
using System; using System.Threading; using System.Threading.Tasks; public class Example { public static void Main() { Thread.CurrentThread.Name = "Main"; // Define and run the task. Task taskA = Task.Run( () => Console.WriteLine("Hello from taskA.")); // Output a message from the calling thread. Console.WriteLine("Hello from thread '{0}'.", Thread.CurrentThread.Name); taskA.Wait(); } } // The example displays the following output: // Hello from thread 'Main'. // Hello from taskA.
AsyncState 属性将其他状态传递到任务时,请使用此方法,如下例所示。
using System;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
Thread.CurrentThread.Name = "Main";
// Better: Create and start the task in one operation.
Task taskA = Task.Factory.StartNew(() => Console.WriteLine("Hello from taskA."));
// Output a message from the calling thread.
Console.WriteLine("Hello from thread '{0}'.",
Thread.CurrentThread.Name);
taskA.Wait();
}
}
// The example displays the following output:
// Hello from thread 'Main'.
// Hello from taskA.