Blog

Filter posts by Category Or Tag of the Blog section!

Task Parallel Library (TPL) in C#

Monday, 12 March 2018

TPL (Task Parallel Library) is a feature in C# that provides a higher-level programming model for writing concurrent and parallel code. It simplifies the process of creating, scheduling, and managing tasks in multi-threaded applications. TPL is part of the .NET framework and was introduced in .NET 4.0. Here are some key components and concepts related to TPL in C#:

 

  • Task: The Task class represents an asynchronous operation or a unit of work that can be executed concurrently. It encapsulates the work to be performed and provides methods for starting, canceling, waiting, and handling the result of the operation.
  •  
  • TaskFactory: The TaskFactory class provides methods for creating and executing tasks. It allows you to specify options and parameters for task creation, such as the cancellation token, scheduling options, and continuation tasks.
  •  
  • TaskScheduler: The TaskScheduler class is responsible for scheduling and executing tasks on available threads or thread pools. It provides different scheduling strategies, such as the default ThreadPoolTaskScheduler, ParallelTaskScheduler, and custom schedulers.
  •  
  • Parallel: The Parallel class provides static methods for performing parallel loops and parallel iterations over collections. It simplifies the process of dividing work among multiple threads and handling synchronization and aggregation of results.
  •  
  • async/await: TPL works seamlessly with the async and await keywords introduced in C# 5.0. They allow you to write asynchronous code in a more readable and structured manner by leveraging tasks and continuations.
  •  

Here's an example that demonstrates the usage of TPL in C#:
 

using System;

using System.Threading.Tasks;



class Program

{

    static async Task Main()

    {

        // Create and start a task asynchronously

        Task<int> task = Task.Run(() => CalculateSum(10));



        // Do some other work concurrently



        // Await the task and get the result

        int result = await task;



        // Print the result

        Console.WriteLine("Sum: " + result);

    }



    static int CalculateSum(int n)

    {

        int sum = 0;

        for (int i = 1; i <= n; i++)

        {

            sum += i;

            // Simulate some work

            Task.Delay(100).Wait();

        }

        return sum;

    }

}

 

In the example, the Task.Run method is used to create and start a task that calculates the sum of numbers asynchronously. The await keyword is used to wait for the task to complete and retrieve the result. Meanwhile, other work can be performed concurrently. Finally, the result is printed on the console.

TPL in C# provides a powerful and efficient way to write concurrent and parallel code, enabling better utilization of hardware resources and improved application performance. It simplifies the complexities of managing threads and synchronization, making it easier to write scalable and responsive applications.

 

Category: Software

Tags: C#

comments powered by Disqus