6

I've got a very simple code snippet, to test how to call Task<> method in Main()

using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
    private static async Task<int> F1(int wait = 1)
    {
        await Task.Run(() => Thread.Sleep(wait));
        Console.WriteLine("finish {0}", wait);
        return 1;
    }

    public static async void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        var task = F1();
        int f1 = await task;
        Console.WriteLine(f1);
    }
}

It doesn't compile because:

(1) F1 is async, so Main() has to be "async".

(2) Compiler says :

error CS5001: Program does not contain a static 'Main' method suitable for an entry point

So if I remove the "async" of Main, compiler will say:

error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

I can either add or remove "async" keyword here. How to make it work? Thanks a lot.

Troskyvs
  • 7,537
  • 7
  • 47
  • 115
  • 5
    _Consider marking this method with the 'async' modifier and changing its return type to 'Task'_ compiler tells you everything already, try to use `public static async Task Main()` – Pavel Anikhouski Mar 02 '20 at 10:29
  • 1
    Does this answer your question? [Can't specify the 'async' modifier on the 'Main' method of a console app](https://stackoverflow.com/questions/9208921/cant-specify-the-async-modifier-on-the-main-method-of-a-console-app) – yaakov Mar 02 '20 at 10:31
  • `Main` with `async` should be returning `Task` not `void` – Ehsan Sajjad Mar 02 '20 at 10:31
  • You need a bootstrap method, perhaps named MainAsync(string[] args) which returns a Task. Then call that method from Main without the need for the async and await reserved words. Ex: MainAsync(args).GetAwaiter().GetResult(); – Ryan Naccarato Oct 12 '22 at 17:01

1 Answers1

18

Your Main method doesn't comply with one of the valid signatures listed here.

You probably want to use this:

public static async Task Main(string[] args)

A Task needs to be returned, so that the runtime knows when the method is complete; this couldn't be determined with void.

The compiler achieves this by generating a synthetic entry point:

private static void $GeneratedMain(string[] args) => 
    Main(args).GetAwaiter().GetResult();
Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35