Parallel Tasks in .NET 4.0

Posted by: Suprotim Agarwal , on 4/5/2010, in Category .NET Framework
Views: 110290
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.
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
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

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel