How to properly use IAsyncDisposable in C#8

Stefan Schranz
ITNEXT

--

C# 8 was a great update for the language, with a lot of new key functionalities for developers to work with. However, with big hitters like nullable reference types and IAsyncEnumerable, there were also a lot of features which fell under the radar.

One of these features, which fills a gap very nicely, is IAsyncDisposable. It is the long missing asynchronous counterpart to IDisposable, and it fills in a very important role in a development world in which asynchronous processing is only getting more and more usage.

What & Why

So, which role does IAsyncDisposable fill exactly? Prior to C#8, developers only had the possibility to use the disposable pattern through the use of the synchronous-only IDisposable interface. For most occurences, this worked just fine. Most of the time, a cleanup/dispose section should be a quick and clean operation.

However, over the time a lot of asynchronous APIs became more and more available, and most of the time the synchronous disposal does not really work well with the API. Generally, developers prefer asynchronous interfaces due to the fact that they don’t block a Thread’s execution. Also, a lot of developers like to use the dispose pattern not only to actually work & clean unmanaged resources, but also to introduce specific scopes with automatic cleanups…

--

--

26 year old full stack software developer from Germany - Enthusiatic about C#, .Net and Cloud — Visit me at https://dotschranz.net/