TPL or Task Parallel Library:
It is a set of public types and APIs, which are under the namespaces of the .Net 4 Framework
System.Threading
System.Threading.Tasks
In short the purpose of the TPL is to make developers more productive by simplifying the process of adding parallelism and concurrency to applications.
Pros:
The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available. The TPL handles the partitioning of the work, the scheduling of threads on the ThreadPool, cancellation support, state management, and other low-level details.
It can maximize the performance of your code while focusing on the work that your program is designed to accomplish.
Cons:
Not all code is suitable
to work in parallel; for example if i have a loop that iterates few times or it
performs a small amount of work, the overhead would be visible in the
performance of the application, causing it to work slower as compared running
the code in serial.
It adds complexity to
the program.
Based on my experience
the threadpool culture may not match the culture of applications that were
upgraded from previous version of .net framework.
To use TPL in our code
first we will add both namespaces:
using System.Threading;
using System.Threading.Tasks;
First let's look at Parallel.Invoke method
try
{
Parallel.Invoke(
() =>
{
SomeMethodA();
},
() =>
{
SomeMethodB();
},
() =>
{
SomeMethodC();
}
);
}
catch (AggregateException
e)
{
string
AggregateError = e. InnerException.ToString();
}
Now, what happens here
is that SomeMethod A, B and C will run concurrently, if you look in the catch
exception I used AggregateException, in TPL you will probably use it more
often. Basically it is used to consolidate
multiple failures into a single, throwable exception object.
No comments:
Post a Comment