Introduction
Task parallelism is the process of running tasks in parallel. Task parallelism divides tasks and allocates those tasks to separate threads for processing. It is based on unstructured parallelism. It means the parallel work unit may start and finish in places scattered according to the the executing of the program.
Why Task? Why not Thread?
Below are the reasons to use Tasks instead of Thread:
The creation of a thread leads to huge costs. It also brings an overhead of context switching within the application. So, it might bring a bad performance issue into a single-core environment.
- If we directly start a thread then it will create a new thread. It will not execute on the thread pool.
Why Task? Why not Thread Pools?
Thread Pool is a wrapper around a pool of threads maintained by the CLR. It does not give any control. You can control the size of the pool but you can't sset anything else.
If you submit too many long-running works to complete to thread pool then it will be full and your work will end up with the finishing up of long-running waiting items. It does not provide any way to find out when a work item has been completed and there's no way to get the result.
It should be used for the short operations and work where the callTer does not need any result.
Task does not create its own new O/S thread as thread pool creates. It allows us to find out when it finishes and to getthe result.
When to not use Thread Pool Thread?
Below are the several cases in which Thread Pool should not be used. It will be better to create and manage your own thread.
- Ifa foreground thread is required.
- If there is a task that causes the thread to block for long periods of time.
Creating Tasks
TPL allows different ways to create tasks. But, te hbelow namespace should be added before creating any tasks:
- using System.Threading.Tasks;
Below are the different ways to create a task:
- Most Direct way:
- Task.Factory.StartNew(() => {Console.WriteLine("Hello Task library!"); });
- Using Action:
- Task task = new Task(new Action(PrintMessage));
- task.Start();
- private void PrintMessage()
- {
- Console.WriteLine("Hello World!");
- }
- Using Delegate:
- task = new Task(delegate { PrintMessage(); });
- task.Start();
- Lambda and named method:
- Task task = new Task( () => MyMessage() );
- task.Start();
- Lambda and anonymous method:
- Task task = new Task( () => { PrintMessage(); } );
- task.Start();
Create Task implicitly
Below are the concepts to create Task implicitly:
- It is maintained by framework.
- It should be used when you need to execute some work which does not return any value and does not need more control over these.
Below is the syntax:
Parallel.Invoke(() => MyFirstWork(), () => MySecondWork());
It provides two methods:
- Parallel.Invoke()
- Parallel.Invoke(ParallelOptions, Action[])
Create Task explicitly
Below are the some concepts to create Task explicitly:
- It is created and maintained by the developer.
- It is being used when we need more control over the tasks or return result.
Below are the two constructors of Task to create Task:
- Task: The Task constructor can be used to create a task where no return value is required. But, it allows us to control other behaviors.
E.g. Task(Action), Task(Action, CancellationToken), Task(Action, TaskCreationOptions), etc.
Namespace:
- System.Threading.Tasks.Task
Example:
- public void MyTasksWithWait()
- {
- Thread.CurrentThread.Name = "Main Thread";
- Task taskA = new Task(() => Console.WriteLine("Hello from Task A"));
-
- taskA.Start();
- Console.WriteLine("Hello from thread {0}", Thread.CurrentThread.Name);
- taskA.Wait();
- }
Output:
Hello from thread Main Thread.
Hellow from thread A.
- Task<TResult>: This constructor allowsus to create a Task with return value. It also allows us to control other behaviors.
E.g. Task<TResult>(Func<TResult>), etc.
Namespace:
- System.Threading.Tasks.Task<TResult>
Example:
- public void TaskReturningResult()
- {
- var t = Task < int > .Run(() =>
- {
-
- int max = 1000000;
- int value = 0;
- for (value = 0; value <= max; value++)
- {
- if (value == max / 2 && DateTime.Now.Hour <= 12)
- {
- value++;
- break;
- }
- }
- return value;
- });
- Console.WriteLine("Finished {0:N0}.", t.Result);
- }
Output:
It will display output as below:
Finished 1,000,001
Conclusion
So, Task Parallelism is a concept of threading wrapper. I will explain its remaining parts in the next article.
Reference
Read more articles on
Multithreading: