To return values from tasks, TPL provides a generic variant of all of the classes that we defined previously:
- Task<T>
- Task.Factory.StartNew<T>
- Task.Run<T>
Once a task finishes, we should be able to get results from it by accessing the Task.Result property. Let's try to understand this using some code examples. We will create various tasks and try to return values from them on completion:
using System;
using System.Threading.Tasks;
namespace Ch02
{
class _2GettingResultFromTasks
{
static void Main(string[] args)
{
GetResultsFromTasks();
Console.ReadLine();
}
private static void GetResultsFromTasks()
{
var sumTaskViaTaskOfInt = new Task<int>(() => Sum(5));
sumTaskViaTaskOfInt.Start();
Console.WriteLine($"Result from...