I have the following C# .NET 5 code. Basically I intend to call the three methods, namely Fun1, Fun2 & Fun3 asynchronously. The 3 methods are independent so are candidate to asynchronous execution. Do I really to use the key word 'await
' here? Because if I use the await keyword while calling Task.Run
method for all the 3 method calls , it will behave synchronously. So I am using Task.WaitAll
instead to wait for all the 3 task runs to complete (block the main thread till all the 3 tasks finish asynchronously). Is there any problem with this approach? I am not sure what would be an alternative method to achieve this using 'await
'. As of now the following code runs in roughly 5 seconds , which shows that it's running asynchronously.
using System;
using System.Threading;
using System.Threading.Tasks;
using static System.Console;
namespace MyTask
{
class Program
{
static async Task Main(string[] args)
{
//Most articles use lamba expression but not sure why as I can directly pass function name to the Run method
//var task1 = Task.Run(()=> { Fun1(); });
//var task2 = Task.Run(()=> { Fun2(); });
//var task3 = Task.Run(()=> { Fun3(); });
var startTime = DateTime.Now;
var task1 = Task.Run(Fun1);
var task2 = Task.Run(Fun2);
var task3 = Task.Run(Fun3);
Task.WaitAll(task1, task2, task3);
var duration = DateTime.Now.Subtract(startTime).TotalSeconds;
WriteLine($"all done --total time taken is {duration}");
}
static int Fun1()
{
WriteLine("Within Fun1");
Thread.Sleep(5000);
return 1;
}
static int Fun2()
{
WriteLine("Within Fun2");
Thread.Sleep(5000);
return 2;
}
static int Fun3()
{
WriteLine("Within Fun3");
Thread.Sleep(5000);
return 3;
}
}
}