Upgrade to C# 7.1

Async Main (C# 7.1)

Another new feature in C# 7.1 is the ability to make a console app deal with Async. Have you ever written a test console app to call an async function; for example, what will this do?

static void Main(string[] args)
{
    MyAsyncFunc();
 
    Console.WriteLine("done");
    
}
 
static async Task MyAsyncFunc()
{
    await Task.Delay(1000);
}

I’m pretty sure that I’ve been asked a question similar to this during an interview, and probably asked the question myself when interviewing others. The way around it in a console app previously was:


static void Main(string[] args)
{
    MyAsyncFunc().GetAwaiter().GetResult();
 
    Console.WriteLine("done");
    
}

However, in C# 7.1, you can do this:


static async Task Main(string[] args)
{
    await MyAsyncFunc();
 
    Console.WriteLine("done");
    
}

Upgrading the Project

Unlike other new features of 7.1, this feature doesn’t afford you the ability to “Control Dot” it. If you try to do this in C# 6, for example, it just won’t compile:

To upgrade, go to the Advanced tab in the Build menu (of project properties):

References

https://github.com/dotnet/roslyn/issues/1695

One thought on “Async Main (C# 7.1)

  1. Nimesh Dhruve

    Thanks, this was driving me crazy, I updated to 4.7.1 but was still getting this error. Your screen shot about Advanced Tab saved me. Thanks again 🙂

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *