Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get return from async method on Task

I’m studying asynchronous programming on C# and I wrote this piece of code:

namespace CSharpThreading
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            Task taskA = MethodToBeCalledParallelly(100);
            Task taskB = MethodToBeCalledParallelly(200);
            Task taskC = MethodToBeCalledParallelly(300);

            int a = await taskA;
            int b = await taskB;
            int c = await taskC;
        }
   
        static async Task<int> MethodToBeCalledParallelly(int extraDelay)
        {
            int totalDelay = 3000 + (int)extraDelay;

            await Task.Delay(totalDelay);
            Console.WriteLine("I was called parallelly");

            return totalDelay;
        }
    }
}

This code is not compiling, what I’m trying to do is to get the return value from the method that I’m calling on the task. Obviously I’m doing something wrong. But I don’t know what. Can someone point me the right direction?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Change Task to Task of int as shown below

namespace CSharpThreading
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            Task<int> taskA = MethodToBeCalledParallelly(100);
            Task<int> taskB = MethodToBeCalledParallelly(200);
            Task<int> taskC = MethodToBeCalledParallelly(300);

            int a = await taskA;
            int b = await taskB;
            int c = await taskC;
        }
   
        static async Task<int> MethodToBeCalledParallelly(int extraDelay)
        {
            int totalDelay = 3000 + (int)extraDelay;

            await Task.Delay(totalDelay);
            Console.WriteLine("I was called parallelly");

            return totalDelay;
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading