Parallel Tasks in .NET 4.0

Posted by: Suprotim Agarwal , on 4/5/2010, in Category .NET Framework
Views: 151925
Abstract: The Parallel class found in the System.Threading.Tasks namespace “provides library-based data parallel replacements for common operations such as for loops, for each loops, and execution of a set of statements”. In this article, we will use the Invoke method of the Parallel class to call multiple methods, possibly in parallel.
In .NET 4.0, we have a set of new API's to simplify the process of adding parallelism and concurrency to applications. This set of API's is called the "Task Parallel Library (TPL)" and is located in the System.Threading and System.Threading.Tasks namespaces.
The Parallel class found in the System.Threading.Tasks namespace “provides library-based data parallel replacements for common operations such as for loops, for each loops, and execution of a set of statements”. In this article, we will use the  Invoke method of the Parallel class to call multiple methods, possibly in parallel.
Update: Also check the following articles:
Follow these steps:
Step 1: Open VS 2010 > File > New Project > Choose ‘Windows’ from the Installed Templates list > Console Application. Give a name to your project and choose a location to save the project.
NewProject
Step 2: Add the following namespaces
C#
using System.Threading;
using System.Threading.Tasks;
 
VB.NET
Imports System.Threading
Imports System.Threading.Tasks
Now write the following three methods which will possibly be called concurrently using Parallel.Invoke()
C#
static void GenerateNumbers()
{
    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine("Method1 - Number: {0}", i);
        Thread.Sleep(1000);
    }
}
 
static void PrintCharacters()
{
    string str = "dotnetcurry";
    for (int i = 0; i < str.Length; i++)
    {
        Console.WriteLine("Method2 - Character: {0}", str[i]);
        Thread.Sleep(1000);
    }
 
}
 
static void PrintArray()
{
    int[] arr = {1, 2, 3, 4, 5, 6, 7, 8 };
    foreach (int i in arr)
    {
        Console.WriteLine("Method3 - Array: {0}", i);
        Thread.Sleep(1000);
    }
}
 
VB.NET
Shared Sub GenerateNumbers()
      For i As Integer = 0 To 9
            Console.WriteLine("Method1 - Number: {0}", i)
            Thread.Sleep(1000)
      Next i
End Sub
 
Shared Sub PrintCharacters()
      Dim str As String = "dotnetcurry"
      For i As Integer = 0 To str.Length - 1
            Console.WriteLine("Method2 - Character: {0}", str.Chars(i))
            Thread.Sleep(1000)
      Next i
 
End Sub
 
Shared Sub PrintArray()
      Dim arr() As Integer = {1, 2, 3, 4, 5, 6, 7, 8 }
      For Each i As Integer In arr
            Console.WriteLine("Method3 - Array: {0}", i)
            Thread.Sleep(1000)
      Next i
End Sub
 
Step 3: In order to call these 3 methods concurrently, we will use Parallel.Invoke() as shown below:
C#
static void Main(string[] args)
{
    Parallel.Invoke(
        new Action(GenerateNumbers),
        new Action(PrintCharacters),
        new Action(PrintArray)
        );
 
    Console.ReadLine();
}
 
VB.NET
Shared Sub Main(ByVal args() As String)
      Parallel.Invoke(New Action(AddressOf GenerateNumbers), New Action(AddressOf PrintCharacters), New Action(AddressOf PrintArray))
 
      Console.ReadLine()
End Sub
Observe how these methods are being called, in parallel
CommandLine
In this article, we used Parallel.Invoke() to call methods that did not return a value. For methods that return a value, you would need to use the Task class which we will explore in one of the forthcoming articles. [Update: Also check the next part of this article Parallel Tasks in .NET 4.0 (Part II) – Methods that Return value  and Cancelling Tasks in .NET 4.0 and
The entire source code of this article can be downloaded over here. I hope you liked the article and I thank you for viewing it.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Hugo on Wednesday, April 7, 2010 10:01 AM
excellent api i must say and nicely explained!
Comment posted by Jamaal on Sunday, April 18, 2010 12:23 AM
Yes this is indeed very simple explained. thansk
Comment posted by ipomz on Monday, April 26, 2010 3:30 AM
thank
Comment posted by prabhat on Tuesday, October 9, 2012 1:25 AM
a+1