ASP.NET Core 6 and IAsyncEnumerable - Async Streamed JSON vs NDJSON

22 lip 2021 | Blog | programowanie | c# | .net | asp.net core | asp.net core mvc | json | ndjson | async | IT

Recently I've published code and written posts about working with asynchronous streaming data sources over HTTP using NDJSON. One of the follow-up questions I've received was how does it relate to async streaming coming in ASP.NET Core 6. As the answer isn't obvious, I've decided to describe the subject in more detail.

ASP.NET Core and IAsyncEnumerable

Since ASP.NET Core 3, IAsyncEnumerable can be returned directly from controller actions.

[Route("api/[controller]")]
[ApiController]
public class WeatherForecastsController : Controller
{
...

[HttpGet("weather-forecast")]
public IAsyncEnumerable<WeatherForecast> GetWeatherForecastStream()
{
async IAsyncEnumerable<WeatherForecast> streamWeatherForecastsAsync()
{
for (int daysFromToday = 1; daysFromToday <= 10; daysFromToday++)
{
WeatherForecast weatherForecast = await _weatherForecaster.GetWeatherForecastAsync(daysFromToday);

yield return weatherForecast;
};
};

return streamWeatherForecastsAsync();
}
}

The ASP.NET Core will iterate IAsyncEnumerable in an asynchronous manner, buffer the result, and send it down the wire. The gain here is no blocking of calls and no risk of thread pool starvation, but there is no streaming of data to the client. If one would like to test this by making some requests, a possible first attempt could look like this.

private static async Task ConsumeJsonStreamAsync()
{
Console.WriteLine($"[{DateTime.UtcNow:hh:mm:ss.fff}] Receving weather forecasts . . .");

using HttpClient

POSTY TEGO AUTORA

Monitoring C# Azure Functions in the Isolated Worker Model - Infrastructure & Configuration Deep Dive26 lis 2024

Blog | programowanie | .net | c# | azure functions | IT

ASP.NET Core 9 and IAsyncEnumerable - Async Streaming JSON and NDJSON From Blazor WebAssembly24 wrz 2024

Blog | programowanie | .net | c# | asp.net core | blazor | IT

Azure Functions Extensibility - Extensions and Isolated Worker Model5 mar 2024

Blog | programowanie | .net | c# | azure functions | azure | IT

Azure Functions Extensibility - Runtime Scaling22 lut 2024

Blog | programowanie | .net | c# | azure | IT

Yet Another Developer Blog

noreply@blogger.com (Tomasz Pęczek)