Reputation: 1916
Microsoft state, "If the SqlConnection goes out of scope, it won't be closed". I don't understand this at all. SqlConnection is an ADO.NET managed object, even if it using an unmanaged resource behind the scenes, so why is the Garbage Collector not cleaning it up? When it goes out of scope it should be destroyed. Can someone please shed some light on this, it's breaking my brain.
Thanks
Upvotes: 1
Views: 906
Reputation: 3805
SqlConnection is disposed when it is finalized. This happens because it inherits from Component, which has a finalizer that calls Dispose. Finalization is one of the steps in garbage collection. Garbage collection runs non-deterministically, i.e. whenever the CLR feels like it. Garbage collection in C# is totally unrelated to an object going out of scope.
So if a SqlConnection goes out of scope, it will at some point in the future be finalized and therefore closed. This is bad because until that finalization hapens, you are wasting resources. Later in your program you might fail to open a connection because too many connections are already open (even though they are not actually in use and just waiting to be finalized).
This is why it is strongly recommended that you Dispose your SqlConnections after you have finished using them.
(Don't read this as a canonical truth of how SqlConnection finalization works. I simplified the details in order to focus on the difference between finalization and explicit disposal).
Upvotes: 2