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.
This article has been editorially reviewed by Suprotim Agarwal.
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!
Was this article worth reading? Share it with fellow developers too. Thanks!
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