Tôi chỉ thấy 3 thói quen liên quan đến việc sử dụng TPL làm cùng một công việc; đây là mã:
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();
}
Tôi chỉ không hiểu tại sao MS cung cấp cho 3 cách khác nhau để chạy các công việc trong TPL vì chúng đều hoạt động như nhau: Task.Start(), Task.Run()và Task.Factory.StartNew().
Tell Me, đang Task.Start(), Task.Run()và Task.Factory.StartNew()tất cả sử dụng cho cùng một mục đích hay họ có ý nghĩa khác nhau?
Khi nào nên sử dụng Task.Start(), khi nào nên sử dụng Task.Run()và khi nào nên sử dụng Task.Factory.StartNew()?
Xin hãy giúp tôi hiểu cách sử dụng thực tế của họ theo kịch bản rất chi tiết với các ví dụ, cảm ơn.
Task.Run- có thể điều này sẽ trả lời câu hỏi của bạn;)