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
Adding a solution that finally solved my problem, hopefully saves somebody's time.
Firstly read a couple articles of Stephen Cleary:
From the "two best practices" in "Don't Block on Async Code", the first one didn't work for me and the second one wasn't applicable (basically if I can use await
, I do!).
So here is my workaround: wrap the call inside a Task.Run<>(async () => await FunctionAsync());
and hopefully no deadlock anymore.
Here is my code:
public class LogReader
{
ILogger _logger;
public LogReader(ILogger logger)
{
_logger = logger;
}
public LogEntity GetLog()
{
Task task = Task.Run(async () => await GetLogAsync());
return task.Result;
}
public async Task GetLogAsync()
{
var result = await _logger.GetAsync();
// more code here...
return result as LogEntity;
}
}