Return 使用 LINQ 的异步任务 select

Return async task using LINQ select

我想实现return 异步从数据库中列出子项目的功能。所以我写了一个函数:

    public async Task<IEnumerable<object>> GetFiles(int parentId)
    {
        var data = from file in DB.Files
                   where file.ParentId == parentId
                   select new { name = file.Name, id = file.Id };
        return data;
    }

但是我可以看到一条警告:异步方法要求 'await' 运算符并将 运行 同步。如何把这个函数改写成异步的?

您可以使用 ToListAsync().

https://msdn.microsoft.com/en-us/library/dn220258(v=vs.113).aspx

var data = await DB.Files
    .Where(file => file.ParentId == parentId)
    .Select
        (
            new 
            { 
                name = file.Name,
                id = file.Id 
            }
        ).ToListAsync();
return data;

或者:

var data = from file in DB.Files
           where file.ParentId == parentId
           select new { name = file.Name, id = file.Id };
return await data.ToListAsync();

请注意,这将查询数据。另外,您可以重新考虑您的方法名称。当一个方法是异步的时,naming convention 建议您将 "Async" 附加到您的方法名称。

By convention, you append "Async" to the names of methods that have an Async or async modifier.

或者你可以使用,TaskCompletionSource -

public static async Task<string> ReturnAsync()
{
    var tsc = new TaskCompletionSource<string>();
    tsc.SetResult("hello world");
    return await tsc.Task;
} 

ToListAsync() method is not working with enumarable anymore. You can use FromResult 方法如下:

var data = from file in DB.Files
           where file.ParentId == parentId
           select new { name = file.Name, id = file.Id };
    return await Task.FromResult(data);