简体   繁体   中英

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!

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 await ing 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM