Calling Async code from sync method

Calling Async code from sync method

Update: C#7.1 and .NET Core 2.0 both now support async Main methods!

Async code is awesome, that's just science. But when you introduce it to a codebase it tends to bubble all the way back up to your entry point

If you're calling an ActionResult in an MVC application then there's no problem, you just make the action method async

public class MyController
{
    public async Task<ActionResult> MyActionAsync()
    {
        return await MyAwesomeAsyncMethod();
    }
}

But if you're using a console application then you have a potential issue. Simply making the entrypoint async gives you this

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

We can instead do the following

using System;
using System.Threading.Tasks;

namespace MyAwesomeAsyncApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            MainAsync(args).GetAwaiter().GetResult();
        }

        public static async Task MainAsync(string[] args)
        {
            await MyAwesomeAyncMethod(args);
        }
    }
}