Below is how my sample application looks like to explore async/await & TPL
class Program
{
static async void Main(string[] args)
{
Console.WriteLine("Order for breakfast");
Breakfast obj = new Breakfast();
Task t1 = Task.Run(() => obj.MakeTea());
Task t2 = Task.Run(() => obj.ToastBread());
Task t3 = Task.Run(() => obj.BoilEgg());
Console.WriteLine("Breakfast ready");
var res = await Task.WaitAll(t1, t2, t3); // LOE - throwing error
}
}
class Breakfast
{
//making a tea
public string MakeTea()
{
return "tea";
}
//toasting bread
public string ToastBread()
{
return "bread";
}
//boil eggs
public string BoilEgg()
{
return "egg";
}
}
at #LOE compiler is throwing build error as
cannot await void
my query here is
How to get rid of this ? Thanks!
First, you should declare the three smaller tasks as Task<string> instead of Task, otherwise you won't get anything in res. Of course, that's not a problem if you don't need anything in res.
The more important issue here is that you should use WhenAll instead of WaitAll. The former returns a Task or Task<T[]> for you to await, whereas the latter just waits for the tasks to finish if they aren't already. Since you are awaiting here, you should use WhenAll.
So your code should be:
Task<string> t1 = Task.Run(() => obj.MakeTea());
Task<string> t2 = Task.Run(() => obj.ToastBread());
Task<string> t3 = Task.Run(() => obj.BoilEgg());
Console.WriteLine("Breakfast ready");
var res = await Task.WhenAll(t1, t2, t3);
// res will contain tea, bread and egg, in some order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With