get1 和 get2 接口的区别是一个加了 async 、await 一个没加的区别,加了 async 、await 会额外生成一些状态机相关的代码,除了这个区别还有其他区别吗?
我的理解是,如果不需要获取异步后的结果进行其他处理则可以不用加。如果不加 async 、await ,真到生产上会不会有什么问题?
示例代码:
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
[HttpGet("get1")]
public Task<Student> Get1Async()
{
return new TsetService().Get1Async();
}
[HttpGet("get2")]
public async Task<Student> Get2Async()
{
return await new TsetService().Get2Async();
}
}
public class TsetService
{
public Task<Student> Get1Async()
{
// 模拟数据库查询
Task.Delay(100);
return Task.FromResult(new Student { Id = 1, Name = "张三" });
}
public async Task<Student> Get2Async()
{
// 模拟数据库查询
await Task.Delay(100);
return new Student { Id = 1, Name = "张三" };
}
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
}
