[英]In ASP.NET Core 6, is an IQueryable returned by a controller action enumerated asynchronously?
My question is similar to Making a Web API controller returning a IQueryable list asynchronous from 2013, and related to Should I call ToListAsync() when make a query .我的问题类似于使 Web API controller 从 2013 年返回一个异步的 IQueryable 列表(当我调用 ToListAsync()时) 。 I want to focus specifically on the claim by multiple users (including the highly regarded Stephen Cleary ) that it is "not necessary" to explicitly enumerate an
IQueryable
asynchronously.我想特别关注多个用户(包括备受推崇的Stephen Cleary )的声明,即“没有必要”显式地异步枚举
IQueryable
。
I know that in recent versions of ASP.NET Core, a controller can return an IAsyncEnumerable
and it will be enumerated asynchronously.我知道在最近版本的 ASP.NET 内核中,一个 controller 可以返回一个
IAsyncEnumerable
并且它将被异步枚举。 Is the answer simply that the framework does the same thing with IQueryable
?答案仅仅是框架对
IQueryable
做同样的事情吗?
And to throw a wrench into what may otherwise be a simple answer, do the potential problems with unbuffered streaming of an IAsyncEnumerable
also apply to IQueryable
?并且为了解决可能是一个简单的答案,
IAsyncEnumerable
的无缓冲流式传输的潜在问题是否也适用于IQueryable
?
IQueryable
doesn't extend IAsyncEnumerable
, but the runtime type of an IQueryable
may be an IAsyncEnumerable
. IQueryable
不扩展IAsyncEnumerable
,但IQueryable
的运行时类型可能是IAsyncEnumerable
。 This is implied by the implementation of AsAsyncEnumerable
. AsAsyncEnumerable
的实现暗示了这一点。
ASP.NET Core does not treat IAsyncEnumerable
or IQueryable
specially. ASP.NET Core 没有特别对待
IAsyncEnumerable
或IQueryable
。 It defers to System.Text.Json
to serialize an object based on its runtime type.它遵循
System.Text.Json
以根据其运行时类型序列化 object。 We can see how that works by searching the source .我们可以通过搜索源代码来了解它是如何工作的。
And System.Text.Json
does not treat IQueryable
specially.而
System.Text.Json
并没有特别对待IQueryable
。 If it happens to be an IAsyncEnumerable
, it will be treated as such.如果它恰好是一个
IAsyncEnumerable
,它将被视为这样。 Otherwise, it will be enumerated synchronously as an IEnumerable
.否则,它将作为
IEnumerable
同步枚举。 So if you want this default behavior, a controller action can simply return an IQueryable
(or Task<IQueryable>
, etc.)所以如果你想要这个默认行为,一个 controller 动作可以简单地返回一个
IQueryable
(或Task<IQueryable>
等)
The only reason to modify the return type is if you know the IQueryable
is an IAsyncEnumerable
, and you want to avoid the potential complications of streaming .修改返回类型的唯一原因是如果您知道
IQueryable
是一个IAsyncEnumerable
并且您希望避免流式传输的潜在复杂性。 In that case, call ToListAsync
to materialize the result in the controller.在这种情况下,调用
ToListAsync
以在 controller 中实现结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.