codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🔷

C# Programming

42 / 60 topics
41Async Programming in C#42Tasks and Task Parallel Library (TPL)43Async and Await Keywords
Tutorials/C# Programming/Tasks and Task Parallel Library (TPL)
🔷C# Programming

Tasks and Task Parallel Library (TPL)

Updated 2026-05-15
10 min read

Tasks and Task Parallel Library (TPL)

Introduction

In the world of C#, handling asynchronous operations efficiently is crucial, especially when dealing with I/O-bound or compute-bound tasks. The .NET framework provides a robust set of tools for managing these tasks through the Task Parallel Library (TPL). This library simplifies the process of writing concurrent and parallel code by providing abstractions like Task, which represents an asynchronous operation.

In this tutorial, we will explore how to use tasks in C# to perform parallel execution. We'll cover the basics of creating and managing tasks, as well as some best practices for using TPL effectively.

Concept

What is a Task?

A Task in .NET represents a single unit of work that can be executed asynchronously. It encapsulates the operation's state, result, and any exceptions that might occur during execution. Tasks are part of the broader asynchronous programming model in C# and are used extensively to perform operations concurrently.

Creating a Task

There are several ways to create a task in C#. The most common methods involve using Task.Run for CPU-bound tasks or Task.Factory.StartNew for more control over task creation. For I/O-bound tasks, you might use asynchronous methods provided by the .NET framework (e.g., HttpClient.GetAsync).

Managing Tasks

Once a task is created, you can manage its execution and retrieve its result. Tasks provide various methods to wait for completion, check their status, and handle exceptions.

Examples

Let's dive into some practical examples to illustrate how tasks work in C#.

Example 1: Basic Task Creation

In this example, we'll create a simple task that performs a CPU-bound operation (calculating the sum of numbers).

csharp
1using System;
2using System.Threading.Tasks;
3
4class Program
5{
6 static async Task Main(string[] args)
7 {
8 // Create and start a new task
9 Task<int> task = Task.Run(() => SumNumbers(1, 1000));
10
11 // Wait for the task to complete and retrieve its result
12 int result = await task;
13
14 Console.WriteLine($"The sum of numbers from 1 to 1000 is: {result}");
15 }
16
17 static int SumNumbers(int start, int end)
18 {
19 int sum = 0;
20 for (int i = start; i <= end; i++)
21 {
22 sum += i;
23 }
24 return sum;
25 }
26}

Example 2: Parallel Execution with Multiple Tasks

In this example, we'll create multiple tasks to perform parallel execution. We'll use Task.WhenAll to wait for all tasks to complete.

csharp
1using System;
2using System.Threading.Tasks;
3
4class Program
5{
6 static async Task Main(string[] args)
7 {
8 // Create an array of tasks
9 Task<int>[] tasks = new Task<int>[]
10 {
11 Task.Run(() => SumNumbers(1, 500)),
12 Task.Run(() => SumNumbers(501, 1000))
13 };
14
15 // Wait for all tasks to complete and retrieve their results
16 int[] results = await Task.WhenAll(tasks);
17
18 // Calculate the total sum
19 int totalSum = results[0] + results[1];
20
21 Console.WriteLine($"The sum of numbers from 1 to 1000 is: {totalSum}");
22 }
23
24 static int SumNumbers(int start, int end)
25 {
26 int sum = 0;
27 for (int i = start; i <= end; i++)
28 {
29 sum += i;
30 }
31 return sum;
32 }
33}

Example 3: Handling Exceptions

In this example, we'll demonstrate how to handle exceptions that might occur during task execution.

csharp
1using System;
2using System.Threading.Tasks;
3
4class Program
5{
6 static async Task Main(string[] args)
7 {
8 // Create a task that might throw an exception
9 Task<int> task = Task.Run(() => SumNumbers(1, 0));
10
11 try
12 {
13 // Wait for the task to complete and retrieve its result
14 int result = await task;
15 Console.WriteLine($"The sum of numbers is: {result}");
16 }
17 catch (DivideByZeroException ex)
18 {
19 Console.WriteLine($"An error occurred: {ex.Message}");
20 }
21 }
22
23 static int SumNumbers(int start, int end)
24 {
25 if (end < start)
26 {
27 throw new DivideByZeroException("End value must be greater than or equal to start value.");
28 }
29
30 int sum = 0;
31 for (int i = start; i <= end; i++)
32 {
33 sum += i;
34 }
35 return sum;
36 }
37}

What's Next?

In the next section, we will explore the async and await keywords in C#, which provide a more elegant way to write asynchronous code. These keywords simplify the syntax for handling tasks and make your code easier to read and maintain.

Stay tuned for more advanced topics in asynchronous programming with C#!


PreviousAsync Programming in C#Next Async and Await Keywords

Recommended Gear

Async Programming in C#Async and Await Keywords