一個普通方法需要用異步方法返回可以用 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;