简体   繁体   English

C#GetAwaiter异步任务<T>

[英]C# GetAwaiter async Task<T>

I am new to using await/async and I have a basic question. 我是使用await / async的新手,但有一个基本问题。 I was able to successfully implement the await/async model in my WebApi Controller and the Business Object (BL) for deletes so in the BL on the Delete method I invoke await entities.SaveChangesAsync(); 我能够在WebApi控制器和业务对象(BL)中成功实现用于删除的await / async模型,因此在BL中,我调用await entities.SaveChangesAsync();Delete方法await entities.SaveChangesAsync(); and updated the method's signature to return public static async Task<ProfileItem> Delete(int profileId, int profileItemId) and this works!!! 并更新了方法的签名,以返回public static async Task<ProfileItem> Delete(int profileId, int profileItemId)并且可以正常工作!!!

Now, I want to do the same when I "fetch" data, so, I have a "getter" and I update the method's signature to public static async Task<List<Property>> GetProperties(int userId, int userTypeId) and here I have some logic that (1) uses the entity framework to retrieve a result set, then I do some stuff and convert my EntityObject into a BusinessObject and return a List<Property> , however when I do return await ... I get the error: List does not contain a definition for 'GetAwaiter' and no extension method ... 现在,我想在“获取”数据时执行相同的操作,因此,我有一个“获取器”,并将方法的签名更新为public static async Task<List<Property>> GetProperties(int userId, int userTypeId) ,在这里我有一些逻辑,即(1)使用实体框架检索结果集,然后执行一些操作,然后将EntityObject转换为BusinessObject并返回List<Property> ,但是当我return await ...错误:列表不包含“ GetAwaiter”的定义,并且没有扩展方法...

Here's the code 这是代码

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

    }

What do I need to do to be able to access the benefits of this functionality in this case. 在这种情况下,我需要做什么才能获得此功能的好处。 Basically I can use Task/async for Saving information to the DB but not getting. 基本上,我可以使用任务/异步将信息保存到数据库,但不能获取信息。 I am sure it is my lack of understanding. 我确信这是我缺乏理解。

Thanks. 谢谢。

You can only use await on "awaitables", which for the most part means Task or Task<T> . 您只能在“ awaitables”上使用await ,这在大多数情况下表示TaskTask<T>

ConvertEntiesToBusinessObj does not return Task<T> , which is fine. ConvertEntiesToBusinessObj不返回Task<T> ,这很好。 It sounds like a synchronous method, so it shouldn't. 听起来像是同步方法,所以不应该。

What you want to do is use ToListAsync instead of ToList , and await that: 您要做的是使用ToListAsync而不是ToList ,然后await

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

Also, as PetSerAI pointed out, it would be more efficient to use ToListAsync once, rather than Any followed by ToList / ToListAsync : 而且,正如PetSerAI所指出的那样,一次使用ToListAsync比使用ToList / ToListAsync之后的Any效率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);
}

The general rule to follow here is to not approach async with the mindset of "I want to make this function async; how do I do this?". 一般的规则在这里遵循的是没有办法async用的心态:“我想使这个功能异步,我该怎么做呢?”。 The appropriate approach is to first identify naturally-asynchronous operations (generally I/O-based) - in this example, the EF queries. 适当的方法是首先识别自然异步操作(通常基于I / O)-在此示例中为EF查询。 Then make those asynchronous and call them with await , and allow async / await to grow naturally from there. 然后使它们异步并使用await调用它们,并允许async / await从那里自然增长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM