如何将方法转换为异步?

时间:2019-04-13 07:24:42

标签: asp.net-mvc

告诉我如何将方法转换为异步方法?

 [HttpGet]
public IActionResult Index()
{
    IEnumerable<CustomerViewModel> customers =
        _customerRepository.GetAllCustomers().Select(s => new CustomerViewModel
        {
            CustomerId = s.CustomerId,
            Name = s.Name,
            Adress = s.Adress
        });
    return View("Index", customers);
}

喜欢吗?

public async Task<IActionResult> Index()

2 个答案:

答案 0 :(得分:3)

创建一个新的异步方法

public interface ICustomerRepository
{
   // add async method to your interface
   Task<IEnumerable<Customer>> GetAllCustomersAsync();
}

public class CustomerRepository : ICustomerRepository
{
  // implementation here
  public async Task<IEnumerable<Customer>> GetAllCustomersAsync()
  {
     return await context.Customer.ToListAsync(); 
  }

}

现在进行异步操作

public async Task<ActionResult> Index()
{
    IEnumerable<Customer> customers =
        await _customerRepository.GetAllCustomersAsync();
    IEnumerable<CustomerViewModel> customersViewModel = customers.Select(s 
         => new CustomerViewModel
        {
            CustomerId = s.CustomerId,
            Name = s.Name,
            Adress = s.Adress
        });
    return View("Index", customersViewModel);
}

答案 1 :(得分:-1)

好吧,我重新制作了GetAllCustomers方法

    public IEnumerable<Customer> GetAllCustomers() 
    { 
        return _db.Customers; 
    } 

GetAllCustomers方法是接口的实现:

    public interface ICustomerRepository
    {
        IEnumerable<Customer> GetAllCustomers(); 
    }

在按照您指定的接口重制了GetAllCustomersAsync方法后,该接口指定了一个错误: “ CustomerRepository”未实现接口成员“ ICustomerRepository.GetAllCustomers()”。 “ CustomerRepository.GetAllCustomers()”无法实现“ ICustomerRepository.GetAllCustomers()”,因为它没有匹配的返回类型“ IEnumerable”。