C# Academy · Lesson

Understanding Threading and Tasks

Explore threading and tasks to manage parallel processing in C#.

Lesson 3 of 510 steps

Understanding Threading and Tasks is a free C# Academy lesson on CoddyKit. This is lesson 3 of 5. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, and your progress syncs across the web and the CoddyKit app. The C# Academy course includes 5 lessons in total.

Introduction to Threading and Tasks

Understanding Threading and Tasks

Welcome to the next lesson! In this lesson, you’ll learn about threading and tasks in C#, which allow you to execute multiple operations concurrently for better performance. Let’s get started!

Understanding Threading and Tasks — illustration 1

What is Threading?

Threading is the process of executing multiple operations simultaneously. Each thread represents a separate flow of control in your application.

Key Point: Threading improves performance by utilizing multiple processor cores for concurrent execution.

Creating and Starting Threads

You can create and start threads using the Thread class. Example:

using System;
using System.Threading;

class Program {
    static void Main() {
        Thread thread = new Thread(PrintNumbers);
        thread.Start();

        Console.WriteLine("Main thread is running...");
    }

    static void PrintNumbers() {
        for (int i = 1; i <= 5; i++) {
            Console.WriteLine(i);
            Thread.Sleep(1000); // Pause for 1 second
        }
    }
}

Introduction to Tasks

Tasks provide a higher-level abstraction for concurrent programming compared to threads. The Task class is part of the Task Parallel Library (TPL) in C#.

Example: Creating and starting a task:

Tip: Tasks are easier to manage and provide better error handling compared to threads.

using System;
using System.Threading.Tasks;

class Program {
    static void Main() {
        Task task = Task.Run(() => {
            for (int i = 1; i <= 5; i++) {
                Console.WriteLine(i);
                Task.Delay(1000).Wait();
            }
        });

        Console.WriteLine("Main thread is running...");
        task.Wait(); // Wait for the task to complete
    }
}

Using Parallel.For and Parallel.ForEach

The Parallel class in C# allows you to execute loops in parallel for better performance. Example:

Key Point: Use Parallel.For and Parallel.ForEach for data-intensive tasks that can be executed concurrently.

using System;
using System.Threading.Tasks;

class Program {
    static void Main() {
        Parallel.For(0, 5, i => {
            Console.WriteLine($"Processing {i} on thread {Task.CurrentId}");
        });

        Console.WriteLine("All tasks completed.");
    }
}

Handling Exceptions in Tasks

You can catch exceptions in tasks using a try-catch block or the Task.Exception property. Example:

using System;
using System.Threading.Tasks;

class Program {
    static void Main() {
        try {
            Task task = Task.Run(() => {
                throw new InvalidOperationException("Task failed!");
            });

            task.Wait();
        } catch (AggregateException ex) {
            Console.WriteLine("Error: " + ex.InnerException.Message);
        }
    }
}

Practice Challenge

Create a program that starts multiple tasks to process numbers in parallel and prints their squares. Example:

using System;
using System.Threading.Tasks;

class Program {
    static void Main() {
        int[] numbers = { 1, 2, 3, 4, 5 };

        Parallel.ForEach(numbers, number => {
            Console.WriteLine($"Square of {number}: {number * number}");
        });
    }
}

Best Practices for Threading and Tasks

Here are some best practices:

  • Prefer Task over Thread for high-level concurrency.
  • Use Parallel classes for data-intensive operations.
  • Handle exceptions properly to ensure robust applications.
  • Limit the number of threads or tasks to avoid resource contention.

Tip: Use async programming when I/O operations dominate, and use threads/tasks for CPU-bound tasks.

Great Job!

Congratulations! You’ve learned the basics of threading and tasks for concurrent programming in C#. In the next lesson, we’ll dive into delegates and lambda expressions, two powerful features for functional programming. Let’s keep coding!

Understanding Threading and Tasks — illustration 10
Free to start

Learn C# with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
93
Lessons
346

Frequently Asked Questions

Is the “Understanding Threading and Tasks” lesson free?

Yes — the full text of “Understanding Threading and Tasks” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO. The C# Academy course includes 5 lessons in total.

What will I learn in “Understanding Threading and Tasks”?

Explore threading and tasks to manage parallel processing in C#. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 5.

How long does the “Understanding Threading and Tasks” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Generics in C#
  2. Async and Await: Working with Asynchronous Code
  3. Understanding Threading and Tasks
  4. Exploring Delegates and Lambdas
  5. Understanding Reflection in C#
← Back to C# Academy