Task Parallel Library (TPL)

TPL is the recent feature in .NET programming for well managed parallel processing.  The main purpose is to increase the developer's productivity by simplifying the programming related to parallelism and concurrency to any enterprise applications.  In my view, it is a highly recommended approach to write parallel processing code in .NET.

In spite of simplicity at TPL, I recommend the programmers to have a basic understanding of the fundamental threading concepts like deadlocks and race conditions. By doing so, TPL will be effectively used in the source code.

Let's start the implementation of TPL with a simple example by simply adding two Threading namespaces:

    using System;
using System.Threading;
using System.Threading.Tasks;

To demonstrate the execution of TPL, let's write two independent methods to display integer and characters of a string, which will be invoked concurrently using the Parallel.Invoke() method:

    static void PostInteger()
{
for (int i=0; i<10; i++)
{
Console.WriteLine("Integer Post:" + i);
Thread.Sleep(500);
}
}
static void PostCharacter()
{
const String sampleText = "Packt Thread";
for (int i = 0; i < sampleText.Length; i++)
{
Console.WriteLine("Character Post:" + sampleText[i]);
Thread.Sleep(1000);
}
}

Now, it is action time to execute the preceding methods concurrently by the following code base using Parallel class:

    using System;
using System.Threading;
using System.Threading.Tasks;

namespace PacktThreadSample
{
class TaskParallel
{
static void PostInteger()
{
for (int i=0; i<10; i++)
{
Console.WriteLine("Integer Post:" + i);
Thread.Sleep(500);
}
}
static void PostCharacter()
{
const String sampleText = "Packt Thread";
for (int i = 0; i < sampleText.Length; i++)
{
Console.WriteLine("Character Post:" + sampleText[i]);
Thread.Sleep(1000);
}
}
static void Main(string[] args)
{
Parallel.Invoke(
new Action(PostInteger),
new Action(PostCharacter)
);
Console.ReadLine();
}
}
}

On executing the preceding source code, it is interesting to observe the highly managed parallelism by .NET framework. From the developer's point of view, the independent parallel methods are constructed and just attached in the Parallel.Invoke method. Without any issue, the application is able to achieve in-built parallelism using simple implementation. The execution result will be as follows:

Thus, TPL supports the well managed parallelism to build .NET enterprise applications. Task parallel library helps the developer community to leverage the full potential of the available hardware capacity. The same code can adjust itself to give you the benefits across various hardware. It also improves the readability of the code and, thus, reduces the risk of introducing challenging parallel process bugs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.27.171