[英]How do I enable asynchronous behavior using async /await while writing API methods in Web API
I have written below ASP.NET API code to return employee data 我已经在ASP.NET API代码下面编写了返回员工数据的代码
public async Task<IActionResult> employeegroups()
{
try
{
var employeegroups = _context.EmployeeGroups.Select(p => new EmployeeGroupsEntity()
{
id = p.Key,
name = p.Name
}).ToList();
return Ok(employeegroups);
}
catch
{
return BadRequest();
}
}
I get this warning: 我收到此警告:
This async method lacks 'await' operators and will run synchronously. 这种异步方法缺少“等待”运算符,将同步运行。 Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread 考虑使用'await'运算符来等待非阻塞API调用,或使用'await Task.Run(...)'在后台线程上进行CPU绑定的工作
So, I tried to add `await': 因此,我尝试添加`await':
var employeegroups = await _context.EmployeeGroups.Select(p => new EmployeeGroupsEntity()
{
id = p.Key,
name = p.Name
}).ToList();
But I get this warning: 但是我得到这个警告:
List 'EmployeeGroupsEntity' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type List 'EmployeeGroupsEntity' could be found (are you missing a using directive or an assembly reference?)" 列表'EmployeeGroupsEntity'不包含'GetAwaiter'的定义,找不到扩展方法'GetAwaiter'接受列表'EmployeeGroupsEntity'类型的第一个参数(您是否缺少using指令或程序集引用?)”
Here is my model: 这是我的模型:
public class EmployeeGroupsEntity
{
public Guid id { get; set; }
public string name { get; set; }
}
When we are working with Task<T>
as return type of method in combination with async
keyword we should also be using await
keyword that will make sure that the calling thread is not blocked and will resume the method lines execution followed after the await
. 当我们将Task<T>
作为方法的返回类型与async
关键字结合使用时,我们还应该使用await
关键字,以确保调用线程未被阻塞,并在await
之后继续执行方法行。 So you should be calling the ToListAsync
method with await
like: 因此,您应该使用await
来调用ToListAsync
方法,例如:
var employeegroups = await _context.EmployeeGroups.Select(p => new EmployeeGroupsEntity()
{
id = p.Key,
name = p.Name
}).ToListAsync();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.