c# async when returning LINQ

会有一股神秘感。 提交于 2020-01-02 07:19:33

问题


I've just realised that this code:

    public async Task<List<Review>> GetTitleReviews(int titleID)
    {
        using (var context = new exampleEntities())
        {
            return await context.Reviews.Where(x => x.Title_Id == titleID).ToList();        
        }
    }

...will not work as async methods cannot await LINQ expressions. I've did some searches but only managed to find some overcomplicated solutions.

How should functions which return LINQ expressions be converted to async versions?


回答1:


Add the System.Data.Entity namespace and take advantage of the Async extension methods

In this case ToListAsync should do the trick

using System.Data.Entity;

public async Task<List<Review>> GetTitleReviews(int titleID)
{
    using (var context = new exampleEntities())
    {
        return await context.Reviews.Where(x => x.Title_Id == titleID).ToListAsync();        
    }
}



回答2:


Technically, that method doesn't return a lambda. It returns a List<Review>.

It's true what you posted won't compile. But this would:

public async Task<List<Review>> GetTitleReviews(int titleID)
{
    using (var context = new exampleEntities())
    {
        return await Task.Run(() => context.Reviews.Where(x => x.Title_Id == titleID).ToList());
    }
}

If that doesn't answer your question, maybe you can be more clear about exactly what you're trying to accomplish and why the above doesn't do it.



来源:https://stackoverflow.com/questions/26643752/c-sharp-async-when-returning-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!