One of the cool new features of C# 7.1 is asynchronous main functions. For many .Net developers it’s not a really big deal, but for those of us that dwell in the dark arcane arts of command line application programming, it is. With Azure’s growing usefulness, small performant CLI app are gaining popularity.

Getting Started

With your tool of choice, create a new WebAPI project. Now that you have your shiny new project we will need to open up the project’s .csproj file and add either <LangVersion>7.1</LangVersion> or <LangVersion>latest</LangVersion> to it, like below:

<PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <LangVersion>latest</LangVersion>
</PropertyGroup>

Note: For ya’ll Windows people out there, you can change the language version in Visual Studio IDE (I’ll be damned if I know how). I am sure you can google it.

Now replace the Main() function in program.cs to public static async Task Main(string[] args) => await BuildWebHost(args).RunAsync(); and Voilà you are now “async all the way”.

Example

using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace AsyncMainDemo
{
    public class Program
    {
        public static async Task Main(string[] args) =>  await BuildWebHost(args).RunAsync();

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
}

Until next time, keep Hackin’.