"ToListAsync()" 和 "AsAsyncEnumerable().ToList()" 之间的区别
Difference between "ToListAsync()" and "AsAsyncEnumerable().ToList()"
函数需要returnTask<List<Record>>
下面两个选项都是returning Task<List<Record>>
,哪个更高效?这里有什么标准的方法吗?
选项 1:
Task<List<Record>> GetRecords()
{
return
DbContext.Set<Record>.Where(predicate).ToListAsync();
}
选项 2:
Task<List<Record>> GetRecords()
{
return
DbContext.Set<Record>.Where(predicate).AsAsyncEnumerable().ToList();
}
请注意,这是 .NET Core 3.x 之前的回答。
在下方@IanKemp 的评论中找到更新。
选择选项 1 ToListAsync
,因为 AsAsyncEnumerable
的 source code 明确提到
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.
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.
虽然 pfx 的现有答案对于 .NET Core 2.x 及更早版本仍然适用,但 AsAsyncEnumerable
已正式添加到 .NET Core 3.x。有关详细信息,请参阅 Ian Kemp 的评论。
函数需要returnTask<List<Record>>
下面两个选项都是returning Task<List<Record>>
,哪个更高效?这里有什么标准的方法吗?
选项 1:
Task<List<Record>> GetRecords()
{
return
DbContext.Set<Record>.Where(predicate).ToListAsync();
}
选项 2:
Task<List<Record>> GetRecords()
{
return
DbContext.Set<Record>.Where(predicate).AsAsyncEnumerable().ToList();
}
请注意,这是 .NET Core 3.x 之前的回答。
在下方@IanKemp 的评论中找到更新。
选择选项 1 ToListAsync
,因为 AsAsyncEnumerable
的 source code 明确提到
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.
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.
虽然 pfx 的现有答案对于 .NET Core 2.x 及更早版本仍然适用,但 AsAsyncEnumerable
已正式添加到 .NET Core 3.x。有关详细信息,请参阅 Ian Kemp 的评论。