简体   繁体   English

在 ASP.NET 核心 6 中,是否由异步枚举的 controller 操作返回的 IQueryable?

[英]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 没有特别对待IAsyncEnumerableIQueryable 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM