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?
>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;
}
}
}