我们平时碰到很多,同步的主程序中需要用到一些工具类是异步的,这样主程序还不能加上异步的 task等标识,就会报错.而直接调用似乎又等不到返回结果.
将调用包装在Task.Run<>(async () => await FunctionAsync());
实际winform 项目内参考的下边的例子 作为备忘
public class LogReader { ILogger _logger; public LogReader(ILogger logger) { _logger = logger; } public LogEntity GetLog() { Task<LogEntity> task = Task.Run<LogEntity>(async () => await GetLogAsync()); return task.Result; } public async Task<LogEntity> GetLogAsync() { var result = await _logger.GetAsync(); // more code here... return result as LogEntity; } }
标签:异步,Task,调用,task,同步,logger,public,await From: https://www.cnblogs.com/zuochanzi/p/17436985.html