【发布时间】:2015-06-23 23:02:34
【问题描述】:
我刚刚看到了 3 个关于 TPL 使用的例程,它们做同样的工作;这是代码:
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();
}
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();
}
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();
}
我只是不明白为什么 MS 提供了 3 种不同的方式在 TPL 中运行作业,因为它们都工作相同:Task.Start()、Task.Run() 和 Task.Factory.StartNew()。
告诉我,Task.Start()、Task.Run() 和 Task.Factory.StartNew() 是否都用于相同的目的,或者它们有不同的意义?
什么时候应该使用Task.Start(),什么时候应该使用Task.Run(),什么时候应该使用Task.Factory.StartNew()?
请通过示例帮助我根据场景详细了解它们的实际用法,谢谢。
【问题讨论】:
-
有一个old article explaining that here 和here for the newer
Task.Run- 也许这会回答你的问题;) -
Here 是
Task.Start实际有用的示例。
标签: c# .net async-await task-parallel-library