用async关键字标记lambda表达式

时间:2019-04-25 12:50:54

标签: c# linq asynchronous async-await expression

我有一个名为GetParentViewModel的函数,如下所示,该函数将Parent模型类转换为ParentViewModel,以便可以将其发送到视图。

Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Built-By: dspicuzz
Created-By: Apache Maven 3.3.9
Build-Jdk: 1.8.0_65
Main-Class: Main

当我尝试在GetParentViewModel中调用GetHobbies和GetFriends的异步函数时,出现错误

   public class Parent
   {
        public int ParentId { get; set; }
        public string ParentName { get; set; }
        public IEnumerable<Child> children{ get; set; }
   }

   public class Child
   {
        public int ChildId { get; set; }
        public string ChildName { get; set; }
        private IEnumerable<Friend> friends { get; set; }
        public IEnumerable<Hobby> hobbies { get; set; }
   }

   public async Task<List<Hobby> GetHobbies(int childId)
   {
       return await..
   }

   public async Task<List<Friend> GetFriends(int childId)
   {
       reutrn await..
   }

   public async Task<ParentViewModel> GetParentViewModel(Parent parentModel)
   {
      return new ParentViewModel() 
      {
         ParentId = parentModel.ParentId,
         ParentName = parentModel.ParentName,
         children = parentModel.children.Select(item => new ChildViewModel()
         {
             ChildId = item.ChildId,
             ChildName = item.ChildName,
             hobbies = await GetHobbies(item.ChildId),
            friends = await GetFriends(item.ChildId)
          }); 
       };
   }

我尝试了各种方法,尝试在“ Select(item => ..”)之前标记为异步,但未成功,在“ children = await parentModel”之后使用了一个await关键字,但它似乎不起作用。 。有人可以帮忙..

我通过编写一个单独的异步函数来获得子级,但没有达到上面的要求。有什么建议吗

谢谢。

1 个答案:

答案 0 :(得分:2)

更新: 我建议将其重构为以下内容:

    public async Task<ParentViewModel> GetParentViewModel(Parent parentModel)
    {
        var childrens = new List<ChildViewModel>();
        foreach (var item in parentModel.children)
        {
            var hobbies = await GetHobbies(item.ChildId);
            var friends = await GetFriends(item.ChildId);

            var child = new ChildViewModel
            {
                ChildId = item.ChildId,
                ChildName = item.ChildName,
                hobbies = hobbies,
                friends = friends
            };

            childrens.Add(child);
        }

        return new ParentViewModel
        {
            ParentId = parentModel.ParentId,
            ParentName = parentModel.ParentName,
            children = childrens
        };
    }