Parallel Tasks in .NET 4.0 (Part II) – Methods that Return value

Posted by: Suprotim Agarwal , on 4/9/2010, in Category .NET Framework
Views: 93944
Abstract: In one of the previous articles Parallel Tasks in .NET 4.0, we explored a set of new API’s called the "Task Parallel Library (TPL)" which simplifies the process of adding parallelism and concurrency to applications. We used the System.Threading.Tasks.Parallel.Invoke() to call methods that did not return a value. However for methods that return a value, you would need to use the Task(TResult) class which represents an asynchronous operation that can return a value. We will explore how to use this class in this article
Parallel Tasks in .NET 4.0 (Part II) – Methods that Return value
 
In one of the previous articles Parallel Tasks in .NET 4.0, we explored a set of new API’s called the "Task Parallel Library (TPL)" which simplifies the process of adding parallelism and concurrency to applications. We used the System.Threading.Tasks.Parallel.Invoke() to call methods that did not return a value. However for methods that return a value, you would need to use the Task(TResult) class which represents an asynchronous operation that can return a value. We will explore how to use this class in this article.
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.




RecentTemplates
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 returns a value and will be called concurrently (possibly) using Task.Start()
C#
static int GenerateNumbers()
{
    int i;
    for (i = 0; i < 7; i++)
    {
        Console.WriteLine("Method1 - Number: {0}", i);
        Thread.Sleep(1000);
    }
    return i;
}
 
static string PrintCharacters()
{
    string str = "dotnet";
    for (int i = 0; i < str.Length; i++)
    {
        Console.WriteLine("Method2 - Character: {0}", str[i]);
        Thread.Sleep(1000);
    }
    return str;
}
 
static int PrintArray()
{
    int[] arr = { 1, 2, 3, 4, 5 };
    foreach (int i in arr)
    {
        Console.WriteLine("Method3 - Array: {0}", i);
        Thread.Sleep(1000);
    }
    return arr.Count();
}
  
VB.NET
Shared Function GenerateNumbers() As Integer
      Dim i As Integer
      For i = 0 To 6
            Console.WriteLine("Method1 - Number: {0}", i)
            Thread.Sleep(1000)
      Next i
      Return i
End Function
 
Shared Function PrintCharacters() As String
      Dim str As String = "dotnet"
      For i As Integer = 0 To str.Length - 1
            Console.WriteLine("Method2 - Character: {0}", str.Chars(i))
            Thread.Sleep(1000)
      Next i
      Return str
End Function
 
Shared Function PrintArray() As Integer
      Dim arr() As Integer = { 1, 2, 3, 4, 5 }
      For Each i As Integer In arr
            Console.WriteLine("Method3 - Array: {0}", i)
            Thread.Sleep(1000)
      Next i
      Return arr.Count()
End Function
 
Step 3: In order to call these 3 methods concurrently and accept return values, we can adopt two approaches
Approach 1: Use the constructor of the Task(Of TResult) class to initialize the task but execute it later. Here’s an example
C#
static void Main(string[] args)
{
    // Create the Tasks
    Task<int> t1 = new Task<int>(GenerateNumbers);
    Task<string> t2 = new Task<string>(PrintCharacters);
    Task<int> t3 = new Task<int>(PrintArray);
    // Start the tasks
    t1.Start();
    t2.Start();
    t3.Start();
    //Print Return Value
    Console.WriteLine("Numbers generated till {0}", t1.Result);
    Console.WriteLine("Original String {0}", t2.Result);
    Console.WriteLine("Array Count {0}", t3.Result);
    Console.ReadLine();
}
 
VB.NET
Sub Main(ByVal args() As String)
      ' Create the Tasks
      Dim t1 As New Task(Of Integer)(GenerateNumbers)
      Dim t2 As New Task(Of String)(PrintCharacters)
      Dim t3 As New Task(Of Integer)(PrintArray)
      ' Start the tasks
      t1.Start()
      t2.Start()
      t3.Start()
      'Print Return Value
      Console.WriteLine("Numbers generated till {0}", t1.Result)
      Console.WriteLine("Original String {0}", t2.Result)
      Console.WriteLine("Array Count {0}", t3.Result)
      Console.ReadLine()
End Sub
Approach 2: We can save a step here and also improve performance by using Task<>.Factory.StartNew() to initialize and execute the task at the same time. Here’s an example
C#
static void Main(string[] args)
{
    // Create and execute the Tasks
    var t1 = Task<int>.Factory.StartNew(() => GenerateNumbers());
    var t2 = Task<string>.Factory.StartNew(() => PrintCharacters());
    var t3 = Task<int>.Factory.StartNew(() => PrintArray());
   
    //Print Return Value
    Console.WriteLine("Numbers generated till {0}", t1.Result);
    Console.WriteLine("Original String {0}", t2.Result);
    Console.WriteLine("Array Count {0}", t3.Result);
    Console.ReadLine();
}
 
VB.NET
Sub Main(ByVal args() As String)
      ' Create and execute the Tasks
      Dim t1 = Task(Of Integer).Factory.StartNew(Function() GenerateNumbers())
      Dim t2 = Task(Of String).Factory.StartNew(Function() PrintCharacters())
      Dim t3 = Task(Of Integer).Factory.StartNew(Function() PrintArray())
 
      'Print Return Value
      Console.WriteLine("Numbers generated till {0}", t1.Result)
      Console.WriteLine("Original String {0}", t2.Result)
      Console.WriteLine("Array Count {0}", t3.Result)
      Console.ReadLine()
End Sub
That’s’ it. Run the application and observe how these methods are being called concurrently and the return value is printed using Task.Result property
ResultProperty
In this article, we used the Task(TResult) class to call methods that returned a value. 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.
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email 
Give me a +1 if you think it was a good article. 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, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Rico on Tuesday, April 13, 2010 2:16 AM
Shouldn't it be a even shoerter To write

    var t1 = Task<int>.Factory.StartNew(GenerateNumbers);
    var t2 = Task<string>.Factory.StartNew(PrintCharacters);
    var t3 = Task<int>.Factory.StartNew(PrintArray);

Just wonder?
Comment posted by Jamorama on Tuesday, April 27, 2010 5:47 AM
really good informative informative to me, as i am tried for long time for such type of script, hopefully may be beneficial to others also.
Comment posted by Abhijit Jana on Sunday, May 9, 2010 4:47 AM
Nice Example.

Thanks Suprotim !
Comment posted by stream direct tv on Tuesday, May 25, 2010 7:18 PM
Hey, this is my 1st time here. Great article, thanks!
Comment posted by Rafiq Ahmed on Wednesday, June 23, 2010 4:41 PM
Very nice article. Very easy to understand.
Comment posted by John on Friday, May 20, 2011 11:01 AM
Thank you for showing the Visual Basic code too!!  :)
Comment posted by Edrian Tomoro on Sunday, January 22, 2012 7:39 AM
Hi,
i've found this vb.net code in the internet, for recording audio file.
///recording
        mciSendString("open new type waveaudio Alias recsound", "", 0, 0)
        unknown = mciSendString("record recsound", "", 0, 0)
///saving
        mciSendString("save recsound c:\recsound.wav", "", 0, 0)
        mciSendString("close recsound", "", 0, 0)
the issue is, I cannot find a way to let the recording process run for X period of time (example 5 minutes)
before it will call for the save process.
can i use Threading here? how?
Comment posted by Benaiah John on Friday, July 13, 2012 12:32 AM
Great article.
I have a doubt though. If the 3 parallel tasks take some time to execute, will program control block before t1.Result, t2.result & t3.result, till all the three tasks have been  completed?

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