In some situations, we may need to run an async method and get its result. But we can't access the await keyword.

  • In the constructor method.
  • When you are implementing an interface sync method.
  • When you are implementing an abstract class sync method.

I got a solution to unwrap the async method and call it in the synchronous method.

First, put the following code anywhere you like:

using System.Threading;
using System.Threading.Tasks;

public static class AsyncHelper  
{
    private static readonly TaskFactory _taskFactory = new
        TaskFactory(CancellationToken.None,
                    TaskCreationOptions.None,
                    TaskContinuationOptions.None,
                    TaskScheduler.Default);

    public static TResult RunSync<TResult>(Func<Task<TResult>> func)
        => _taskFactory
            .StartNew(func)
            .Unwrap()
            .GetAwaiter()
            .GetResult();

    public static void RunSync(Func<Task> func)
        => _taskFactory
            .StartNew(func)
            .Unwrap()
            .GetAwaiter()
            .GetResult();
}

And create an async method like this:

private static async Task<int> MyAsyncMethod()
{
    // do something async.
    await Task.Delay(1000);
    Console.WriteLine("Running in MyAsyncMethod");
    return 2 + 3;
}

To call the async method: MyAsyncMethod in a sync method, do it like this:

static void Main(string[] args)
{
    var result = AsyncHelper.RunSync(async () =>
    {
        return await MyAsyncMethod();
    });
    Console.WriteLine(result);
}

Which outputs:

Running in MyAsyncMethod
5

Or more simply:

var result = AsyncHelper.RunSync(MyAsyncMethod)
Console.WriteLine(result);

Which outputs the same:

Running in MyAsyncMethod
5