Return a Value from a Task in C#

How to Return a Value from a Task in C# with Examples

In this article, I am going to discuss How to Return a Value from a Task in C# with some examples. Please read our previous article where we discussed how to create and use the task object in C# in different ways.

The .NET Framework also provides a generic version of the Task class i.e. Task<T>. Using this Task<T> class we can return data or value from a task. In Task<T>, T represents the data type that you want to returns as a result of the task.

Example:

In the following example, the CalculateSum method takes an input integer value and calculate the sum of the number starting from 1 to that number. Here the CalculateSum method returns a double value. As the return value from the CalculateSum method is of double type, so here we need to use Task<double> as shown in the below example.

using System;
using System.Threading.Tasks;

namespace TaskBasedAsynchronousProgramming
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"Main Thread Started");

            Task<double> task1 = Task.Run(() => 
            {
                return CalculateSum(10);
            });
            
            Console.WriteLine($"Sum is: {task1.Result}");
            Console.WriteLine($"Main Thread Completed");
            Console.ReadKey();
        }

        static double CalculateSum(int num)
        {
            double sum = 0;
            for (int count = 1; count <= num; count++)
            {
                sum += count;
            }
            return sum;
        }
    }
}

Output:

How to Return a Value from a Task in C#

Note: The Result property of the Task object blocks the calling thread until the task finishes its work.

Example2:

In the below example, we are writing the logic as part of the Anonymous method.

using System;
using System.Threading.Tasks;
namespace TaskBasedAsynchronousProgramming
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"Main Thread Started");

            Task<double> task1 = Task.Run(() => 
            {
                double sum = 0;
                for (int count = 1; count <= 10; count++)
                {
                    sum += count;
                }
                return sum;
            });
            
            Console.WriteLine($"Sum is: {task1.Result}");
            Console.WriteLine($"Main Thread Completed");
            Console.ReadKey();
        }
    }
}

It will also give you the same output as the previous example. So, whenever your logic is a few lines and that is going to be used only once, then it always better to write the logic with the anonymous method.

Example3: Returning Complex Type Value From a task

In the below example, we are returning a Complex type.

using System;
using System.Threading.Tasks;

namespace TaskBasedAsynchronousProgramming
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"Main Thread Started");
            Task<Employee> task = Task<Employee>.Factory.StartNew(() =>
            {
                Employee employee = new Employee()
                {
                    ID = 101,
                    Name = "Pranaya",
                    Salary = 10000
                };

                return employee;
            });
            Employee emp = task.Result;

            Console.WriteLine($"ID: {emp.ID}, Name : {emp.Name}, Salary : {emp.Salary}");
            Console.WriteLine($"Main Thread Completed");
            Console.ReadKey();
        }
    }

    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public double Salary { get; set; }
    }
}

Output:

How to Return Complex Type Value From a task in C#

That’s it for today. In the next article, I am going to discuss Chaining Tasks by Using Continuation Tasks in C# with some examples. Here, in this article, I try to explain how to return a value from a task with some examples. I hope you enjoy this article.

Leave a Reply

Your email address will not be published. Required fields are marked *