Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of Cannot await 'void' in C#

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

  1. I don't have methods as void still why it is throwing such error?
  2. Why can't void be await?

How to get rid of this ? Thanks!

like image 753
Kgn-web Avatar asked Dec 29 '25 22:12

Kgn-web


1 Answers

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.
like image 200
Sweeper Avatar answered Dec 31 '25 11:12

Sweeper