Understanding Task Parallel Library

Tutorial 3 of 5

Understanding Task Parallel Library

1. Introduction

Tutorial's Goal

This tutorial aims to provide an in-depth understanding of the Task Parallel Library (TPL) in C#. By the end of this tutorial, you will have a firm grasp on how to use TPL to optimize your code's performance by executing multiple operations simultaneously.

What the User Will Learn

  • The fundamentals of the Task Parallel Library.
  • How to create tasks and handle exceptions.
  • How to use the Parallel class for parallel loops.
  • How to manage and synchronize tasks.

Prerequisites

You should have fundamental knowledge of C# programming and a basic understanding of threading.

2. Step-by-Step Guide

Understanding Tasks

A Task represents a single operation that does not return a value and that usually executes asynchronously. Task instances are created by the Task.Factory.StartNew method, or the shortcut Task.Run method.

Here's an example:

Task task = Task.Run(() => 
{
    // Your code here.
});

Exception Handling

When an exception occurs within a task, it's not thrown immediately. Instead, it's stored and thrown when you attempt to access the task's result or explicitly wait for the task.

try
{
    task.Wait();
}
catch(AggregateException ae)
{
    // Handle the exception here.
}

Parallel Class

The Parallel class includes parallel versions of for and foreach loops, called "Parallel.For" and "Parallel.ForEach".

Parallel.For(0, 10, i => 
{
    // Your code here.
});

3. Code Examples

Creating a Simple Task

Task newTask = Task.Run(() => 
{
    Console.WriteLine("This is a simple task.");
});
newTask.Wait(); // Wait for the task to finish.

// Expected output: "This is a simple task."

Handling Exceptions in Tasks

Task newTask = Task.Run(() => 
{
    throw new InvalidOperationException("Error in task.");
});

try
{
    newTask.Wait();
}
catch(AggregateException ae)
{
    foreach(var e in ae.InnerExceptions)
    {
        Console.WriteLine(e.Message);
    }
}

// Expected output: "Error in task."

4. Summary

In this tutorial, we've covered the basics of the Task Parallel Library in C#, including tasks creation, exception handling, and the use of the Parallel class for loop parallelism.

The next steps for learning could involve diving deeper into advanced topics like cancellation tokens, task continuations, and data parallelism.

5. Practice Exercises

  1. Create a task that computes the sum of an array of integers.
  2. Modify the first exercise to use the Parallel.For loop. Measure the time taken for both tasks. Which one is faster?
  3. Handle exceptions in a task. What happens when an exception is thrown inside a task?

Remember, practice is key when it comes to mastering parallel programming with the TPL. Happy coding!