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

后端 未结 15 1040
星月不相逢
星月不相逢 2020-11-21 06:27

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

15条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 06:43

    Adding a solution that finally solved my problem, hopefully saves somebody's time.

    Firstly read a couple articles of Stephen Cleary:

    • Async and Await
    • Don't Block on Async Code

    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;
        }
    }
    

提交回复
热议问题