C# / C# Multithreading and Concurrency

Parallel Programming in C#

In this tutorial, we will delve into parallel programming in C#. You'll learn how to break down tasks into independent subtasks that can be processed simultaneously, improving you…

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Explores multithreading concepts and techniques for concurrent execution in C#.

1. Introduction

This tutorial aims to introduce you to the concept of parallel programming in C#. We'll break down tasks into independent subtasks that can be processed simultaneously to improve your application's performance.

By the end of this tutorial, you will:
- Understand the basics of parallel programming in C#
- Be able to write your own parallel programs in C#
- Know how to optimize your programs for better performance

Prerequisites

This tutorial assumes you have a basic understanding of C# programming. If you're new to C#, you may want to first go through a basic C# tutorial.

2. Step-by-Step Guide

Parallel programming is about executing multiple tasks at the same time. This is done by dividing a problem into discrete, independent tasks that can be executed in parallel.

Basic Concepts

In C#, the System.Threading.Tasks namespace provides the Parallel class, which has static methods for parallel implementations like For and ForEach loops.

Parallel.For loop

The Parallel.For loop works just like a regular for loop, but the iterations are executed in parallel:

Parallel.For(0, 10, i => {
    Console.WriteLine(i);
});

Parallel.ForEach loop

The Parallel.ForEach loop is a parallel version of the foreach loop:

var numbers = new List<int> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Parallel.ForEach(numbers, number => {
    Console.WriteLine(number);
});

Task class

The Task class 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:

Task.Factory.StartNew(() => {
    // Code to execute in parallel
});

Best Practices and Tips

  • Always try to use the Parallel.For or Parallel.ForEach loops when you can, because they're easier to use and read.
  • Be careful with shared data. When multiple tasks are accessing and changing the same data, it can lead to unpredictable results.

3. Code Examples

Example 1: Parallel.For loop

Parallel.For(0, 10, i => {
    Console.WriteLine($"Parallel.For: {i}");
});

This code will print the numbers from 0 to 9 in no particular order, because the iterations are being executed in parallel.

Example 2: Parallel.ForEach loop

var numbers = new List<int> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Parallel.ForEach(numbers, number => {
    Console.WriteLine($"Parallel.ForEach: {number}");
});

This code will print the numbers from the list in no particular order, because the iterations are being executed in parallel.

4. Summary

In this tutorial, you learned about parallel programming in C#. You learned how to use the Parallel.For and Parallel.ForEach loops and the Task class to execute code in parallel.

Next Steps

To further your understanding of parallel programming in C#, you should try to apply these concepts in your own projects.

Additional Resources

5. Practice Exercises

These exercises will help you practice the concepts you've learned.

  1. Write a program that uses a Parallel.For loop to print the numbers from 0 to 100.
  2. Write a program that uses a Parallel.ForEach loop to print all the elements in a list of strings.
  3. Write a program that uses the Task class to execute three different operations in parallel.

Solutions and Explanations

  1. This code will print the numbers from 0 to 100 in no particular order:
Parallel.For(0, 101, i => {
    Console.WriteLine(i);
});
  1. This code will print all the strings from the list in no particular order:
var strings = new List<string> {"one", "two", "three", "four", "five"};
Parallel.ForEach(strings, str => {
    Console.WriteLine(str);
});
  1. This code will execute three operations in parallel:
Task.Factory.StartNew(() => {
    Console.WriteLine("Task 1");
});
Task.Factory.StartNew(() => {
    Console.WriteLine("Task 2");
});
Task.Factory.StartNew(() => {
    Console.WriteLine("Task 3");
});

Tips for Further Practice

Try to use parallel programming in your own projects, and experiment with different numbers of tasks to see how it affects the performance.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help