I have a public async void Foo()
method that I want to call from synchronous method. So far all I have seen from MSDN documentation is calling async methods via
Inspired by some of the other answers, I created the following simple helper methods:
public static TResult RunSync(Func> method)
{
var task = method();
return task.GetAwaiter().GetResult();
}
public static void RunSync(Func method)
{
var task = method();
task.GetAwaiter().GetResult();
}
They can be called as follows (depending on whether you are returning a value or not):
RunSync(() => Foo());
var result = RunSync(() => FooWithResult());
Note that the signature in the original question public async void Foo()
is incorrect. It should be public async Task Foo()
as you should return Task not void for async methods that don't return a value (yes, there are some rare exceptions).