Skip to main content

ASP.NET Core–Performance tip

Question: What is wrong with the following ASP.NET Core controller:

No idea?

Take a look at the return type...

Returning IEnumerable from an action results in synchronous collection iteration by the serializer. The result is the blocking of calls and a potential for thread pool starvation.

One possible way to avoid this is by explicitly invoking ToListAsync before returning the result:

Starting from ASP.NET Core 3.0 you can also use IAsyncEnumerable<T>. This no longer results in synchronous iteration and is as efficient as returning IEnumerable<T>.

Let’s rewrite the example above to use IAsyncEnumerable<T>:

REMARK: If we take a look at the original example again, it will not be an issue in ASP.NET Core 3.0 or higher. Why? Because we allow the framework to choose how to handle the IQueryable<T> we get back from the Where() clause. In the situation we are using ASP.NET Core 3.0 or higher the results will be buffered and correctly provided to the serializer. However this is implicit behavior that doesn’t work in all situations(it depends on the underlying types used).

More information and other performance tips can be found here: https://docs.microsoft.com/en-us/aspnet/core/performance/performance-best-practices