Return Value From Task
A task that does not return a value is represented by the System.Threading.Tasks.Task
class.
A task that returns a value is represented by the System.Threading.Tasks.Task<TResult>
class, which inherits from Task.
Returning a Simple Value
// var task1 = Task.Run(() => 5*2);
// or
var task1 = Task<int>.Run(() => 5*2);
Console.WriteLine(task1.Result);
Accessing the Result property blocks the calling thread until the task finishes.
Returning an Object
var task2 = Task<Employee>.Run(() => {
return new Employee { Id = 1, Name = "Gandhi"}
});
var emp = task2.Result;
Console.WriteLine($"{emp.Id} {emp.Name}");
class Employee {
public int Id {get; set;}
public string Name {get; set;}
}
Returning a Tuple
var task3 = Task.Run<(int Id, string Name)>(() => (2, "Anna"));
var emp2 = task3.Result;
Console.WriteLine($"{emp2.Id} {emp2.Name}");