一个普通方法需要用异步方法返回可以用 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;
本文探讨了在C#中如何使用Task.FromResult()和Task.Run()从普通方法返回异步结果,以及如何通过(GetTask).GetAwaiter().GetResult()在同步上下文中调用异步方法。提供了具体代码示例,包括ResultZeroAsync和ResultNumberAsync两个异步方法的实现。
1462

被折叠的 条评论
为什么被折叠?



