145-c-sharp-parallel-threading-example

To use paralleling of the treads in C#, we need to use System.Threading.Tasks; namespace.

There are several ways to parallelize threads, including usage of PLINQ. In here, for educational purpose most simple c# parallel threading example as console application is given.

Function that is to be called in parallel thread has to be declared as
static public void

So let’s make a simple function for calculating square of the integer and writes it to console:

static public void _write_square(int a)
{

int _square;
_square = a * a;
Console.WriteLine(_square.ToString());

}

If we want to call this function to find first 20 squares, we can declare int array

int[] _array = new int[20];
for (int i = 1; i <= 20; i++)
{

_array[i – 1] = i;

}

If _write_square(int a) is called in sequentional manner (not parallel) it can be called

foreach (int i in _array)
{

_write_square(i);

}

In here, calling of void function goes with passing by argument. However, we want to have parallel threads, parameters to function will not be passed explicitly.

Parallel.ForEach(_array, _write_square);
Console.ReadLine();

Whole code is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Parallelizm
{

class Program
{

static void Main(string[] args)
{

int[] _array = new int[20];
for (int i = 1; i <= 20; i++)
{

_array[i – 1] = i;

}
foreach (int i in _array)
{

_write_square(i);

}
Parallel.ForEach(_array, _write_square);
Console.ReadLine();

}
static public void _write_square(int a)
{

int _square;
_square = a * a;
Console.WriteLine(_square.ToString());

}

}

}

External links:

C# Parallel Threading Example on Microsoft
C# Parallel Threading Example on Albahari

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*