Represented by:
Important Note:
- Runs the task immediately after creating the task .This type of execution is known as Task Parallelism.
- Runs the task in a pre-defined order. This type of execution is known as Continuation Tasks.
- Running the task by pair. That is in Asynchronous programming model.
Now let’s look deep into Task Parallelism.
- Task parallel library is used to perform asynchronous operation.
- The task that are invoked by Task Parallelism is invoked by are independent of one another.
- Parallel.Invoke(() => Console.WriteLine("Perform Operatrion 1"), () =>Console.WriteLine("Perform Operatrion 2"));
- The Task are separated by “,”. They are independent of one another.
- These task are actually queued in ThreadPool.
- It provides many enhancements such as waiting, cancellation, continuations, exception handling, detailed status, custom scheduling, and more.
- It takes Action delegate as input, that is the return type is always void.
- Task.Run method create and start a task in one operation, that is in one step.
- TaskFactory.StartNew is also used to create and start a task in one operation.
Code sample
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Task_Parallel_Library {
- class Program {
- static void Main(string[] args) {
- runoperation obj = new runoperation();
- Console.WriteLine("Creating and running tasks implicitly");
- obj.parallelinvoke_implicitly();
- Console.WriteLine();
- Console.WriteLine("Creating and running tasks explicity");
- obj.parallelinvoke_explicity_01();
- Console.WriteLine();
- Console.WriteLine("Creating and running tasks explicity by referencing action delegate");
- obj.parallelinvoke_explicity_03();
- Console.ReadLine();
- }
- }
- class runoperation {
- static runoperation() {}
- public void parallelinvoke_implicitly() {
-
-
-
-
- Parallel.Invoke(() = > Console.WriteLine("Perform Operatrion 1"), () = > Console.WriteLine("Perform Operatrion 2"));
- }
- public void parallelinvoke_explicity_01() {
- Parallel.Invoke(() = > dowork("Task- One"), () = > dowork("Task- Two"), () = > dowork("Task- Three"));
- }
- private void dowork(string input) {
- Console.WriteLine("I have been called by '{0}'", input);
- }
- public void parallelinvoke_explicity_03() {
-
- Parallel.Invoke(action1);
- }
-
-
-
- Action action1 = new Action(delegate {
- Console.WriteLine("Hi.... I am action Delegate.... I am inline coded with anonymous type");
- });
- }
- }