Creating and Running Tasks
A task can be created either explicitly or implicitly.
When you create a task, you give it a user delegate that encapsulates the code that the task will execute. The delegate can be expressed as a named delegate
, an anonymous method
, or a lambda expression
.
Implicitly
Using Parallel.Invoke
The Parallel.Invoke method provides a simple way to run a task. You can also run any number of tasks concurrently.
Parallel.Invoke(() => Console.WriteLine("Hello from task."));
Explicitly
Task class provides static and instance methods to create a task.
Namespace: System.Threading.Tasks
Assembly: System.Runtime.dll
Using Task.Run static method
Task taskA = Task.Run(() => Console.WriteLine("Hello from task."));
taskA.Wait();
Task.Wait
method is called to ensure that the task completes execution before the console application ends.
use the Task.Run methods to create and start a task in one operation. To manage the task, the Run methods use the default task scheduler, regardless of which task scheduler is associated with the current thread.
Using new Task
Task taskA = new Task(() => Console.WriteLine("Hello from task."));
taskA.Start();
taskA.Wait();
Using Task.Factory.StartNew
Task taskA = Task.Factory.StartNew(() => Console.WriteLine("Hello from Task"));
taskA.Wait();
When to use
- When creation and scheduling do not have to be separated
- When you require additional task creation options or the use of a specific scheduler
- When you need to pass additional state into the task that you can retrieve through its
Task.AsyncState
property