Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Member-only story

Types of Parallelism in C#

Jay Krishna Reddy
Level Up Coding
Published in
3 min readAug 9, 2024

Parallelism is an essential concept in modern computing, and it enables us to achieve significant performance gains by performing multiple tasks simultaneously. In C#, there are several types of parallelism that developers can leverage to optimize their code and increase its efficiency. In this article, we will explore the most common types of parallelism in C#, along with examples of their implementation.

  1. Task Parallelism

Task Parallelism is a form of parallelism that involves breaking down a large task into smaller, independent sub-tasks that can be executed simultaneously. In C#, the Task Parallel Library (TPL) provides a high-level abstraction for creating and managing tasks.

Here is an example of Task Parallelism in C#:

using System;
using System.Threading.Tasks;

class Program
{
static void Main()
{
Task[] tasks = new Task[10];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = Task.Factory.StartNew(() => Console.WriteLine("Task {0} running", i));
}

Task.WaitAll(tasks);
}
}

In this example, we create an array of 10 tasks, and each task executes the same lambda expression, which prints out a message indicating that it is running. We then wait for all tasks to complete using the WaitAll method.

2. Data Parallelism

Data Parallelism involves dividing a large data set into smaller chunks and processing them in parallel. This is a common technique for optimizing algorithms that involve large amounts of data processing.

In C#, the Parallel class provides a set of methods for performing data parallelism, such as Parallel.For and Parallel.ForEach.

Here is an example of Data Parallelism in C#:

using System;
using System.Threading.Tasks;

class Program
{
static void Main()
{
int[] data = new int[10000000];

Parallel.For(0, data.Length, i =>
{
data[i] = i * i;
});
}
}

In this example, we use the Parallel.For method to iterate over an array of integers and square each element in parallel. The method automatically divides the work into smaller chunks and assigns them to separate threads for parallel processing.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

Write a response