Asynchronous Dispose
After the advent of Tasks in .NET, most of the libraries managing I/O operations progressively moved to an asynchronous behavior. For example, the System.Net.Websocket
class members embrace the Task-based programming strategy, providing a better developer experience and more efficient behavior.
Every time a developer needs to write a C# client to access some service based on the WebSocket protocol, they typically write a wrapper class exposing specialized send methods and implementing the dispose pattern to invoke the Websocket.CloseAsync
method. We also know that any asynchronous method should return a Task
, but the Dispose method has been defined as void far before the Task
era, and therefore doesn't fit well in the Task
chain.
The Websocket example is very realistic as I had this exact problem some time ago, where blocking the current thread to wait for the CloseAsync to finish inside the Dispose caused a deadlock.
Starting from C# 8 and .NET Core...