我正在尝试以异步方式运行我的控制器操作。 如何使用异步任务?或如何以异步方式运行
// Db context
public class DeptContext : DbContext
{
public LagerContext(DbContextOptions<LagerContext> options)
: base(options)
{
Database.Migrate();
}
public DbSet<Department> Departments { get; set; }
public DbSet<Product> Products { get; set; }
}
这是我的接口 IDepRepository
Task<Department> GetDepartmentWithOrWithoutProducts(int deptId, bool includeProducts);
和我的存储库类 DepRepository
public class DepRepository : IDepRepository
{
private DeptContext db;
public DepRepository(DeptContext context)
{
db = context;
}
// I'am geting Department name with products or Without products
public async Task<Department> GetDepartmentWithOrWithoutProducts(int deptId, bool includeProducts)
{
if(includeProductss)
{
return await db.Departments.Include(c => c.Products).Where(s => s.deptId == deptId).SingleAsync();
}
return await db.Departments.Where(s => s.deptId == deptId).SingleAsync();
}
}
那么我现在应该如何在我的控制器中以异步方式执行此操作:我尝试如下,但我不知道这样做是否正确: 我没有收到任何错误,但如果方式正确,我不会...
using System.Threading.Tasks;
using System.Net;
using Microsoft.Data.Entity;
using Microsoft.EntityFrameworkCore;
[Route("api/departments")]
public class DepartmentsController : Controller
{
private IDeptRepository _deptInfoRepository;
public DepartmentsController(IDeptRepository deptInfoRepository)
{
_deptInfoRepository = deptInfoRepository;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetDepatment(int id, bool includeProducts = false)
{
var dept = _deptInfoRepository.GetDepartmentWithOrWithoutProducts(id, includeComputers);
if(dept == null)
{
return BadRequest();
}
if(includeProducts)
{
var depResult = new DepartmentDto() { deptId = dept.deptId, deptName = dept.deptName };
foreach(var department in dept.Products)
{
depResult.Products.Add(new ProductDto() { productId = department.productId, deptId = department.deptId, ProductName = department.ProductName });
}
return Ok(depResult);
}
var departmentWithoutProductResult = new DepartmentsWithoutProductsDto() { DeptId = dept.deptId, DeptName = dept.DeptName};
return Ok(departmentWithoutProductResult);
}
我该怎么做才能以异步方式获取我的控制器。我不知道把那些 await 和 ToListAsync(( 放在哪里。提前谢谢你!
应重命名界面以更好地显示意图。
public interface IDepRepository {
Task<Department> GetDepartmentWithOrWithoutProductsAsync(int deptId, bool includeProducts);
//...
}
这将相应地更新实现。由于该方法在异步调用后实际上并未使用任何内容,因此实际上没有任何理由将该方法标记为异步。只需返回任务即可。
public Task<Department> GetDepartmentWithOrWithoutProductsAsync(int deptId, bool includeProducts) {
if(includeProductss) {
return db.Departments.Include(c => c.Products).Where(s => s.deptId == deptId).SingleAsync();
}
return db.Departments.Where(s => s.deptId == deptId).SingleAsync();
}
但是,控制器操作需要等待任务,然后在任务完成后继续,因此该方法将被标记为异步。
[HttpGet("{id}")]
public async Task<IActionResult> GetDepatment(int id, bool includeProducts = false) {
var dept = await _deptInfoRepository.GetDepartmentWithOrWithoutProductsAsync(id, includeComputers);
if (dept == null) {
return BadRequest();
}
if (includeProducts) {
var depResult = new DepartmentDto() { deptId = dept.deptId, deptName = dept.deptName };
foreach (var department in dept.Products) {
depResult.Products.Add(new ProductDto() {
productId = department.productId,
deptId = department.deptId,
ProductName = department.ProductName
});
}
return Ok(depResult);
}
var departmentWithoutProductResult = new DepartmentsWithoutProductsDto() { DeptId = dept.deptId, DeptName = dept.DeptName};
return Ok(departmentWithoutProductResult);
}
我无法从您的代码中分辨出的是 GetDepartments 返回的数据类型。我的猜测是,您正在使用EF Core,并且GetDepartments针对DbSet返回DbSet或LINQ查询。如果是这种情况,则在设置 depEntities 变量的行之后,该变量指向延迟对象(尚未评估的表达式树(。或者换句话说,实际查询尚未发送到数据库。当您遍历 depEntities(使用 foreach 循环(时,会导致实际的潜在长时间运行的工作发生(数据库访问(。这就是你想要等待的。所以,是的,你可以制作一个异步版本的GetTDepartment,或者你也可以将你的代码更改为:
var depEntities = await _depRepository.GetDepartments().ToListAsync();
对 ToListAsync 的调用将枚举延迟对象并执行数据库访问。您的返回语句只会返回结果。在后台,该方法实际上返回您的 await 语句,并在您等待的工作完成后恢复。
最后一点......任何数据库异常都将发生在枚举延迟对象的点。
你不应该对已经准备好的results
列表做任何await
。它已经包含所需的数据 - 您想等待什么?
您应该制作GetDepartments()
方法的新异步版本,并在从存储库获取数据时等待:
var depEntities = await _depRepository.GetDepartmentsAsync();