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: 145757
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 

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 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?
Comment posted by Good post, can you help me on Tuesday, December 23, 2014 11:39 AM
I need to make a sql backup bus this take 5 minutes to done. I think this code can help me to whait to backup done and continue with other process. I use VB 2010 but in this line "Dim t1 As New Task(Of Integer)(GenerateNumbers)" show this "A value integer can't change in to System.Func(Of Integere)"