Tôi chỉ thấy 3 thói quen liên quan đến việc sử dụng TPL mà làm cùng công việcVề sử dụng Task.Start(), Task.Run() và Task.Factory.StartNew()
đâ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 đưa ra 3 cách khác nhau để chạy công việc trong TPL vì tất cả chúng đều hoạt động giống nhau: Task.Start()
, Task.Run()
và Task.Factory.StartNew()
.
Cho tôi biết, là Task.Start()
, Task.Run()
và Task.Factory.StartNew()
tất cả được sử dụng cho cùng một mục đích hoặc chúng có ý nghĩa khác nhau?
Khi nào nên sử dụng Task.Start()
, khi Task.Run()
và khi nào thì nên sử dụng Task.Factory.StartNew()
?
Hãy giúp tôi hiểu cách sử dụng thực tế của họ theo từng trường hợp chi tiết với ví dụ, cảm ơn.
có một [bài viết cũ giải thích rằng tại đây] (http://blogs.msdn.com/b/pfxteam/archive/2010/06/13/10024153.aspx) và [tại đây cho tác vụ mới hơn 'Task.Run '] (http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx) - có thể điều này sẽ trả lời câu hỏi của bạn;) – Carsten
[Here] (http://stackoverflow.com/a/21427264/1768303) là một ví dụ về nơi 'Task.Start' thực sự hữu ích. – Noseratio