Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to call asynchronous method from synchronous method in C#?

I have a public async void Foo() technique that I need to call from an asynchronous strategy. So far all I have seen from MSDN documentation is calling async techniques by means of async strategies, yet my entire program isn't worked with async techniques.

Is this even possible?
by

2 Answers

rahul07
async Main is now part of C# 7.2 and can be enabled in the projects advanced build settings.

For C# < 7.2, the correct way is:

static void Main(string[] args)
{
MainAsync().GetAwaiter().GetResult();
}


static async Task MainAsync()
{
/await stuff here/
}
pankajshivnani123
Solution A

If you have a simple asynchronous method that doesn't need to synchronize back to its context, then you can use Task.WaitAndUnwrapException:

var task = MyAsyncMethod();
var result = task.WaitAndUnwrapException();

You do not want to use Task.Wait or Task.Result because they wrap exceptions in AggregateException.

This solution is only appropriate if MyAsyncMethod does not synchronize back to its context. In other words, every await in MyAsyncMethod should end with ConfigureAwait(false). This means it can't update any UI elements or access the ASP.NET request context.

Solution B

If MyAsyncMethod does need to synchronize back to its context, then you may be able to use AsyncContext.RunTask to provide a nested context:

var result = AsyncContext.RunTask(MyAsyncMethod).Result;

Login / Signup to Answer the Question.