Monday, June 14, 2021

.NET 6 Preview 4: Async Streaming in ASP.NET Core

In this post, let's go through another feature that got introduced to ASP.NET Core in .NET 6 Preview 4. That is Async Streaming.

Before looking at how Async Streaming works in .NET 6, let's first have a look at how it works in the current version: .NET 5. I have created a simple API targetting .NET 5 that returns an IAsyncEnumerable<T>.
[ApiController]
[Route("[controller]")]
public class ValuesController : ControllerBase
{
    [HttpGet]
    public IAsyncEnumerable<intGet()
    {
        IAsyncEnumerable<intvalue = GetData();
        return value;
    }

    private static async IAsyncEnumerable<intGetData()
    {
        for (var i = 1; i <= 10; i++)
        {
            await Task.Delay(1000);
            yield return i;
        }
    }
}
Here if you run this, first the results would be buffered into memory before being written into the response. So you will get the response after like ~10 seconds. Something like this.
IAsyncEnumerable<T> streaming .NET 5
Now let's change the target framework to .NET 6 and run the same code. 
IAsyncEnumerable<T> streaming .NET 6
Isn't it nice? So what's happening here is, IAsyncEnumerable<T> instances are no longer buffered into the memory before it gets written out into the response. But there is something very important to note here, this functionality will only work if you are using System.Text.Json as the serializer, because this functionality is actually made possible by System.Text.Json as it now has support for streaming IAsyncEnumerable<T> types. If you are using NewtonsoftJson as your serializer, things will not work as shown above.


Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment