Usage of Parallel Programing in .NET
In the modern world, we are using multi-core processor devices such as PC, Laptop and mobile, etc. In the multi-threading applications, we are only using the single processor from the multi-core processor, using a single processor of multi-core processor you may not achieve the full functionality performances and benefits from a particular multi-core processor. So, the Parallel Program runs task/query parallelly in the different core processor of the multi-core processor, now the executions will be even faster as the earlier multi-threaded applications.
1. Task Parallel Library
Task Parallel Library is a set of public types and APIs based on a concept of a task, as we can describe a task as an object representing an ongoing computation. The following diagram shows the logical working internal handling process of the parallel requests.
1.1 Creating Task
By reading this section you will get a brief idea about the types of tasks and task creation. We have two ways of creating a task as Implicit and Explicit.
Implicit : Parallel.Invoke
An implicit way is achieved by using Parallel.Invoke method which provides a convenient way to run any number of statements concurrently. The easiest way to create the statements more precisely delegates is by using lambda expressions.
Explicit : Task.Run
Use directly a task class instance, task can be created as a void instance that does not return a value by using System.Threading.Tasks.Task class or as wants that returns some values by using System.Threading.Tasks.Task<TResult> class.
To understand the parallelism of the TPL let’s see below code snippets.
As you can see the above explicit way of created tasks, when run the code we can see the result for the very 1st time as bellow
The program stopped and run again then we get the following results.
As a summary of the above results, as you can observe the result orders are not the same on a number of program execution, and each task is executed in different threads that is how the parallelism works.
1.2 Wait Task
Situations can occur, that we might need to wait for dependent tasks to complete before we proceed with the next tasks. Have a look at the following code snippet
Result of above code as follow
If we run this code multiple times which will give the same set of results. The reasons for this the task 1 and task 2 have the wait method to executes one after another.
1.3 Return a Value from a Task
Following image shows how to get result from a Task
According to the above picture, task1 returns an integer value and saves that in a variable also the task2 returns a vehicle type object and saves in a variable. Please note getting a result from a task is a blocking operation and will pause the application until the result is not received.
1.4 Task cancellation
By reading this section you will get a basic idea of how to cancel a task and task within a task using a cancellation token. Using System.Threading.Tasks.Task and System.Threading.Tasks.Task<IResult> classes support cancellation operation through the use of cancellation tokens. The cancellation token can be created by using the cancelation token source.
Following code shows the status of cancellation token when the cancellation has not been requested for task1 and task 2.
Result of the above code as you can see the status of cancellations is false in both tasks.
Next, we call the cancel method from the source object after task 1 and adding a delay before the move to task2.
As you can see the bellow image shows the results of the above code, after task1 we have called the cancel method then the task 2 status changed to true which means the has been canceled.
The following image shows how we can use cancellation within a task.
Cancellation only affected task 3 we have called the cancellation in task 2, task 1, and task to get executed before the cancellation so task 3 is called with the 7-sec delay so the cancellation requested before task 3 starts and status changed as “True”. The following image shows the output
1.5 Exception Handling
Here, if we used try catch inside the task, it would not be detectable to the main program. Therefore, the solution is to add it around the Wait call. This will then propagate the exception thrown by the task to the catch statement. We can then use the aggregate exception type to check the exception and handle it. The following image shows the code and results.
Result of above code as follow.
1.6 Importance of Using TPL
TPL helps to utilize the tasks in proper manner. But there are some benefits why you should consider when developing and application let’s have a look.
- It makes developers more productive by simplifying the process of adding parallelism and concurrency to applications.
- Task Parallel Library is based on the concept of a task, which represents an asynchronous operation.
- The Task Parallel Library handles the partitioning of the work.
- Scheduling of threads on the Thread Pool.
- Cancellation support.
- State management and other low-level details.
- By using Task Parallel Library, can maximize the performance of your code while focusing on the work that your program is designed to accomplished.
As a result, the above are some benefits of using TPL, so there are more benefits then the mentioned ones. Choosing wisely will help to improve your application’s performance.
2. PLINQ (Parallel LINQ)
PLINQ provides support for Parallel programming and is closely associated to the Task Parallel Library. Parallel LINQ is a parallel implementation of LINQ to Objects which enables query to automatically take advantage of multiple processors. Therefor the query performance can be increased significantly by using all available cores on the host server. Following diagram will show you how the PLINQ works.
2.1. Example using PLINQ
In the following example we are extracting all even numbers within the sourceData. To achieve this, we will use PLINQ mechanism.
In the following image uses the AsParallel() method which creates an instance of the ParallelQuery class. This extension method makes sure that the parallel features are used.
Run the following code we will get the all integers without any sequence order. This is the result of the Parallel execution of the query. If we remove the AsParallel() method then we will get ascending order of results, and will be displayed. So that we can get a basic understanding of how the PLINQ works with queries in parallel.
2.2 Limitations of PLINQ
- PLINQ only works against local collections.
- Since PLINQ chunks the collection into multiple partitions and executes them in parallel, the results that you would get from a PLINQ query may not be in the same order as the results that you would get from a serially executed LINQ query.
3. Async and Await
When we talk about parallel programing must need to look this topic, plays a big role in the parallel programing by using Aync and Await. Asynchronous is just opposite work of synchronous, that means Async do not wait for any particular task to finish, can perform some other task on the same interface, so the end user does not wait until for the 1st task to finish.
Following are some keywords you need to know while writing any Async method.
3.1. Basic example for Async & Await
Following image shows two methods, which are not dependent on each other.
The created TaskOne method and TaskTwo method are independent and now we are calling those methods in the main method, following image will show the result of above code.
As the result of above we can clearly say that both methods are not waiting to each other it runs parallelly. So as a summary, by using async/ await creates asynchronous methods to the applications which runs independently without waiting for one another so the application run even faster than earlier.
3.2 Benefits of Async/Await
- Increase the performance and responsiveness of the application.
- Async / Await is the newer replacement to BackgroundWorker, which has been used on windows forms desktop applications.
- Async / Await improvements added to the feature like foreach async and generalized async type like ValueTask.
- Organize your code in a neat and readable way with
async
/await
, you write less code and your code will be more maintainable than using the previous asynchronous programming methods such as using plain tasks.
Conclusion
So far by reading this blog hope you got brief idea about Parallel Program. Main intention of this blog is to get a quick idea about Parallel program and how it works and how you can apply to the code base and some of its benefits. Parallel Program is more use useful when we need to perform any parallel task in a modern technology and devices. There are some more resources available to read and get more idea about Parallel Program you can follow up Dot Net official documentation.