8

I would like to change Main method to async, but I don't know how to edit this method, since it is "invisible" in .NET 6.0. I want it to look something like this: static async Task Main(string[] args). So how can I edit it?

Reza Heidari
  • 1,192
  • 2
  • 18
  • 23
Glaurung
  • 105
  • 1
  • 5
  • 2
    It's only 'invisible' if you choose to use C# that way. You can still create a namespace/class/main if you want to. – Neil May 01 '22 at 16:10

1 Answers1

23

If you want to stick with top-level statements, you don't need to change anything. Just use await within your top-level statements, and the compiler will generate an async method for you.

If you'd prefer to write your own class declaration, that's absolutely fine. So for example, this is fine:

await Task.Delay(1000);
Console.WriteLine($"Hi {args[0]}");

... and so is this:

namespace MyNamespace;

class Program
{
    static async Task Main(string[] args)
    {
        await Task.Delay(1000);
        Console.WriteLine($"Hi {args[0]}");
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194