C#GetAwaiter异步任务<t>

时间:2016-12-25 17:27:40

标签: c# .net asynchronous async-await

我是使用await / async的新手,我有一个基本的问题。我能够在我的WebApi控制器和业务对象(BL)中成功实现await / async模型以进行删除,因此在Delete方法的BL中我调用了await entities.SaveChangesAsync();并更新了方法&#39; s签名返回public static async Task<ProfileItem> Delete(int profileId, int profileItemId),这有效!!!

现在,我希望在我&#34; fetch&#34;数据,所以,我有一个&#34; getter&#34;并且我将方法的签名更新为public static async Task<List<Property>> GetProperties(int userId, int userTypeId),这里我有一些逻辑:(1)使用实体框架来检索结果集,然后我做了一些事情并将我的EntityObject转换为BusinessObject并返回一个List<Property>,但当我return await ...时,我收到错误:列表中没有包含&#39; GetAwaiter&#39;的定义没有扩展方法...

这是代码

public static async Task<List<Property>> GetProperties(int userId, int userTypeId)
    {

        entities = new MyEntities();

        var userType = entities.sl_USER_TYPE.Where(_userType => _userType.ID == userTypeId).First();


        var properties = entities.sl_PROPERTY.Where(_property => _property.USER_ID == userId && _property.USER_TYPE_ID == userTypeId);

        if (!properties.Any())
            throw new Exception("Error: No Properties exist for this user!");

        // here is where I get the error
        return await ConvertEntiesToBusinessObj(properties.ToList(), userId);

    }

在这种情况下,我需要做些什么才能获得此功能的好处。基本上我可以使用Task / async将信息保存到数据库但不能获取。我确信这是我缺乏理解。

感谢。

1 个答案:

答案 0 :(得分:3)

您只能在“awaitables”上使用await,这在很大程度上意味着TaskTask<T>

ConvertEntiesToBusinessObj不会返回Task<T>,这很好。这听起来像是一种同步方法,所以不应该这样。

您要做的是使用ToListAsync代替ToList,使用await

return ConvertEntiesToBusinessObj(await properties.ToListAsync(), userId);

此外,正如PetSerAI指出的那样,使用ToListAsync一次,而不是Any后跟ToList / ToListAsync会更有效:

public static async Task<List<Property>> GetProperties(int userId, int userTypeId)
{
  entities = new MyEntities();
  var userType = await entities.sl_USER_TYPE.Where(_userType => _userType.ID == userTypeId).FirstAsync();
  var properties = await entities.sl_PROPERTY.Where(_property => _property.USER_ID == userId && _property.USER_TYPE_ID == userTypeId).ToListAsync();

  if (!properties.Any())
    throw new Exception("Error: No Properties exist for this user!");

  return ConvertEntiesToBusinessObj(properties, userId);
}

此处遵循的一般规则是接近async,其思维方式为“我想让此功能异步;我该怎么做?”。适当的方法是首先识别自然异步操作(通常基于I / O) - 在本例中,EF查询。然后将那些异步并使用await调用它们,并允许async / await从那里自然增长。

相关问题