ASP.NET Core 6.0 Features

Last Updated: 5/16/2022

IAsyncDisposable

Overview

  • IAsyncDisposable is now available for Controllers, Razor Pages, and View Components. You can now asynchronously dispose resources.
  • IAsyncDisposable is beneficial when working with Asynchronous enumerators (eg Asynchronous Streams) and Unmanaged resources that have resource-intensive I/O operations to release.
  • You should use IAsyncDisposable if your class (or any of its subclasses) allocates resources that implement IAsyncDisposable
  • When implementing this interface, use the DisposeAsync method to release resources.
public class HomeController : Controller, IAsyncDisposable
{
    private Utf8JsonWriter? _jsonWriter;
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
        _jsonWriter = new Utf8JsonWriter(new MemoryStream());
    }
    
    public async ValueTask DisposeAsync()
	{
	    if (_jsonWriter is not null)
	    {
	        await _jsonWriter.DisposeAsync();
	    }

	    _jsonWriter = null;
	}
}    

References:

https://www.infoworld.com/article/3649352/how-to-work-with-iasyncdisposable-in-net-6.html