问题
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();
}
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/56176176/difference-between-tolistasync-and-asasyncenumerable-tolist