Search code examples
c#asynchronousado.netasync-awaitdbconnection

Why there's no `DBconnection.CloseAsync()` while there is `DBconnection.OpenAsync()`?


I'm changing our DAL to an async DAL.

Looking at :

await _conn.OpenAsync().ConfigureAwait(false);

I see that there's an async method for open connection.But why there's no async method for closing connection ?

  • A shared connection might used by others
  • Might return to the connection pool
  • It is an I/O operation
  • Possible delayed / time-consuming operation

(I might be wrong about all four above :-))

Question

It seems logic ( to me) that there's should be an async close method for a connection.

Is there a reason why there's not ?

PS I will obviously will use DAPPER at the end , but just for practicing , I've decided to create small mini mini dapper alike DAL.


Solution

  • A shared connection might used by others

    Why would this make calling close on it take a long time? If anything this would mean that, in cases where the connection is still being used by others all that "closing" it means is indicating that you no longer needed it, and the actual underlying connection doesn't need to be closed.

    It is an I/O operation

    Not necessarily. As you said, if it's pooled/shared, then it's just returned to the pool, no IO would happen at all.

    And what makes you think that, even if the underlying connection is being closed, that it would take a long time. All that needs to happen is to stop paying attention to the connection, possibly sending a courtesy message through the connection saying that you're done. That's not going to take a long time. You don't need to wait for any type of response to such a message, so you aren't waiting for a completed network round trip in this method.

    Possible delayed / time-consuming operation

    Why would it be time consuming? If it is delayed (if, for example, the connection is pooled and you're closing it when you're the last user of it) it means that that it'll likely be closed after a bit, but you aren't needing to wait for that.

    Marking an object as "no longer in use" simply isn't time consuming, and at the end of the day that's all you're really doing.