Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly are the resources used when querying a database and why do they need disposing?

Tags:

c#

sql

When looking at the proper way to query a database in C#, I often see this advise:

Make sure you dispose the Reader, Command, and Connection object

If I look at the documentation of SqlConnection, SqlCommand and SqlDataReader, all what I can see as description for Dispose method is

Releases all resources used by the Component.

I want to know what resources are used by these 3 types mentioned above. I thought only disposing SqlConnection will dispose and close other two nested objects(SqlCommand and SqlDataReader).

Also, there is many MSDN examples not disposing SqlCommand object. See this example

So, I have two main concerns here:

  1. What precise resources are used for each type?
  2. What are the consequences of not properly disposing each one of them?

I know that connection with database is unmanaged code and is not properly handled by garbage collector. I would like to know, what object or resources are used by each object and what will happen exactly if I don't dispose each one of them.

So PLEASE don't answer something general like unmanaged code, garbage collector, free resources...

like image 669
Mhd Avatar asked Dec 06 '25 08:12

Mhd


1 Answers

  1. This can change. The difference is they are unmanaged (think c instead of c#) and so we are basically just informing the unmanaged component it should release ANY resources it used... This includes closing open connections, freeing memory (as unmanaged code does not get the benefit of the garbage collector), closing handles it has requested from the operating system.

  2. Memory leaks mostly. Half open connections on the database side. Failed code reviews and jibes from more experienced developers :P

Try read: https://msdn.microsoft.com/en-us/library/498928w2(v=vs.110).aspx

like image 197
Milney Avatar answered Dec 08 '25 20:12

Milney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!