如何使用async Task <iactionresult>?或者如何在我的Asp.Net Core Web Api中以异步方式运行

时间:2017-07-01 20:26:33

标签: c# asp.net-core asp.net-core-webapi

我正试图以异步方式运行我的Controller Action。 我如何使用异步任务?或者如何以异步方式运行

// 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; }


}

//这是我的Interface IDepRepository

Task<Department> GetDepartmentWithOrWithoutProducts(int deptId, bool includeProducts);

//我的Repository类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);


    }

如何让我的控制器以异步方式运行..我不知道在哪里等待和ToListAsync()。提前谢谢!

3 个答案:

答案 0 :(得分:0)

您不应在已准备好的await列表中执行任何results。它已经包含了所需的数据 - 您想要等待的内容?

您应该创建GetDepartments()方法的新异步版本并等待从存储库获取数据:

var depEntities = await _depRepository.GetDepartmentsAsync();

答案 1 :(得分:0)

我从代码中无法判断的是GetDepartments返回的数据类型。我的猜测是你正在使用EF Core和GetDepartments对DbSet返回DbSet或LINQ查询。如果是这种情况,则在设置了depEntities变量的行之后,该变量指向延迟对象(尚未评估的表达式树)。或者换句话说,实际查询尚未发送到数据库。当您遍历depEntities(使用foreach循环)时,您将导致实际可能长时间运行的工作(数据库访问)。这就是你想要等待的东西。所以,是的,您可以创建GetDepartments的异步版本,或者您也可以将代码更改为:

var depEntities = await _depRepository.GetDepartments().ToListAsync();

对ToListAsync的调用将枚举延迟对象并执行数据库访问。您的退货声明只会返回结果。在幕后,该方法实际上会在您的await语句中返回,并在您正在等待的工作完成后继续。

最后一个注释..任何数据库异常都将在枚举延迟对象的位置发生。

答案 2 :(得分:0)

应重命名界面以更好地显示意图。

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);
}