Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "ToListAsync()" and "AsAsyncEnumerable().ToList()"

Function need to return Task<List<Record>> Following both options are returning Task<List<Record>>, which one is more efficient? Is there any standard way here?

Option 1 :

Task<List<Record>> GetRecords()
{
    return 
    DbContext.Set<Record>.Where(predicate).ToListAsync();
}

Option 2:

Task<List<Record>> GetRecords()
{
    return
    DbContext.Set<Record>.Where(predicate).AsAsyncEnumerable().ToList();
}

like image 640
Nainesh Patel Avatar asked May 16 '19 20:05

Nainesh Patel


2 Answers

While the existing answer by pfx is still true for .NET Core 2.x and earlier, AsAsyncEnumerable has been added to .NET Core 3.x officially. See Ian Kemp's comment for further info.

like image 138
André Reichelt Avatar answered Oct 12 '22 12:10

André Reichelt


Note that this is a pre .NET Core 3.x answer.
Find an update in the comment of @IanKemp here below.

Go for option 1 ToListAsync as the source code of AsAsyncEnumerable explicitly mentions

This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release. You should only use it directly in your code with extreme caution and knowing that doing so can result in application failures when updating to a new Entity Framework Core release.

The official documentation mentions

This API supports the Entity Framework Core infrastructure and is not intended to be used directly from your code. This API may change or be removed in future releases.

like image 7
pfx Avatar answered Oct 12 '22 12:10

pfx