3
votes

As per this post, the top voted answer suggested that we can use async directly in main. Or I misunderstood it?

Can't specify the 'async' modifier on the 'Main' method of a console app

My main class:

public class Program
{
    public static async Task Main(string[] args)
    {
        ApproveEvents ap = new ApproveEvents();
        List<MyModel> result = new List<MyModel>();
        result = await ap.ApproveAsync();
        if (result.count > 0)
        {
            //do something here
        }

    }
}

And,

public class ApproveEvents
{
    public async Task<List<MyModel>> ApproveAsync()
    {
        //blah blah
    }
}

Visual Studio 2017 is complaining about no Main method for an entry point.

How should I resolve this?

2
Try pointing your app to the latest .net framework on your project properties. - Hackerman
project -> properties -> build -> Advanced -> Language version, make sure something is selected that is greater than or equal to 7.1, you made need to fiddle depending on what you have (latest Major release may not work) - TheGeneral
Note that the visual-studio tag description says "DO NOT use this tag on questions regarding code which merely happened to be written in Visual Studio." Please edit your question to remove it. - Richardissimo

2 Answers

6
votes

async Task Main is available in C# 7.1. You can change it in build properties (the default is the latest major version, which is 7.0)

2
votes

i'd recommend you looking at this topic to help you, it speaks right into your issue.

it stated:

As I showed above, if you want to await an async operation in the entrypoint method, you need to apply some workaround, because the following entrypoint definition is invalid:

public static async Task Main(string[] args) 
{ 
    await BuildWebHost(args).RunAsync(); 
}

in order to make this work you will need to do the following workaroung:

public static void Main(string[] args)
{     
    BuildWebHost(args).RunAsync().GetAwaiter().GetResult();
}

or calling wait() on the task object itself:

public static void Main(string[] args)
{
    BuildWebHost(args).RunAsync().Wait();
}

there is a list of valid entry points in C# 7.1, this is the up to date list:

public static void Main();
public static int Main();
public static void Main(string[] args);
public static int Main(string[] args);
public static Task Main();
public static Task<int> Main();
public static Task Main(string[] args);
public static Task<int> Main(string[] args);