For Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Threading.Tasks;
namespace URLRoutingDemoApp.Parallel_For
{
public partial class ParallelInvokeWithReturnValue : System.Web.UI.Page
{
static string stValues = string.Empty;
string strTaskResult = string.Empty;
string strTaskResult1 = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
stValues = "";
strTaskResult = "";
strTaskResult1 = "";
//Two Approaches
//Approach 1-> First Initialize the task and then execute
Task
Task1.Start();
Task2.Start();
Task3.Start();
strTaskResult += "Task1=" + Task1.Result.ToString() + "</br>";
strTaskResult += "Task1=" + Task2.Result.ToString() + "</br>";
strTaskResult += "Task1=" + Task3.Result.ToString() + "</br>";
lblparallelInvokewithreturnvalue.Text = stValues + "::::</br>" + strTaskResult;
//Approach 2-> Initialize and execute task at the same time
stValues = "";
var TaskApp1=Task
strTaskResult1 += "Task1=" + TaskApp1.Result.ToString() + "</br>";
strTaskResult1 += "Task1=" + TaskApp2.Result.ToString() + "</br>";
strTaskResult1 += "Task1=" + TaskApp3.Result.ToString() + "</br>";
lblparallelInvokewithreturnvalue1.Text = stValues + "::::</br>" + strTaskResult1;
}
static int GenerateNumbers()
{
int i;
for (i = 0; i < 10; i++)
{
stValues += "Method1 - Number " + i.ToString() + " </br>";
Thread.Sleep(1000);
}
return i;
}
static string PrintCharacters()
{
string str = "blog";
for (int i = 0; i < str.Length; i++)
{
stValues += "Method2 - Character " + str[i].ToString() + " </br>";
Thread.Sleep(1000);
}
return str;
}
static int PrintArray()
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
foreach (int i in arr)
{
stValues += "Method3 - Array " + i.ToString() + " </br>";
Thread.Sleep(1000);
}
return arr.Count();
}
}
}
Used the Task(TResult) class to call methods that returned a value.