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.
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
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.
Give me a +1 if you think it was a good article. Thanks!