在.NET Core的Controller
中,您可以Ok()
作为IActionResult
返回。但我不明白它如何也能返回Task<IActionResult>
。
示例:
public class FooController : Controller
{
[HttpGet]
public async Task<IActionResult> OkResultAsync()
{
// This is ok. But I don't get why since OkResult != Task<IActionResult>
OkResult result = Ok();
return result;
}
[HttpGet]
public IActionResult OkResult()
{
// This is ok, and it seems logical since OkResult implements IActionResult.
OkResult result = Ok();
return result;
}
[HttpGet]
public FooResult Bar()
{
// This is ok.
return new FooResult();
}
[HttpGet]
public async Task<FooResult> BarAsync()
{
// This is not ok since FooResult != Task<FooResult>
return new FooResult();
}
}
Ok()
会返回OkResult
,而会生成IActionResult
。如果方法签名返回Task<IActionResult>
,.NET如何知道如何处理它(无需等待?)
答案 0 :(得分:4)
async
关键字使编译器自动处理此问题。隐式的异步方法&#34; wrap&#34;任务中的返回值。
async Task<int> GetNumber()
{
return 42;
}
VS
Task<int> GetNumber()
{
return Task.FromResult(42);
}
答案 1 :(得分:1)
async关键字是一种在Task中包装方法内容的简写。当您在异步方法内部返回时,编译器会将其包装到您的任务中。例如,这两种方法基本相同:
private static Task<string> Hello()
{
return new Task<string>(() => "hello");
}
private static async Task<string> AsyncHello()
{
return "hello";
}