一个普通方法需要用异步方法返回可以用 Task.FromResult() 和 Task.Run() 。
一个异步方法需要在普通方法中调用时,可以用 (Task).GetAwaiter().GetResult() 来获取同步值。
static async void Main(string[] args)
{
int a = await ResultZeroAsync();
int b = ResultZeroAsync().GetAwaiter().GetResult();
}
static async Task<int> ResultZeroAsync()
{
return await Task.FromResult(0);
}
static async Task<int> ResultNumberAsync()
{
return await Task.Run(() => ResultZero());
}
static int ResultZero() => 0;