Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# does calling Dispose delete the object from Heap?

Tags:

c#

dispose

If I do a conn.Dispose(); (where conn is an instance of a SqlConnection Class), will that clear the conn object from the heap?

like image 775
developer747 Avatar asked Jan 03 '12 16:01

developer747


1 Answers

No, calling Dispose doesn't clear the connection from the heap. When you call the Dispose method on a SqlConnection instance all you do is return the connection to the underlying connection pool. It doesn't even close the connection. ADO.NET uses a connection pool. So when you create a new instance of SqlConnection you do not open a new connection, you simply draw a connection from the connection pool and when you call Dispose you simply return this connection to the connection pool so that it can be reused.

In general the IDisposable pattern in .NET is intended to be implemented by classes that hold some pointers to some unmanaged resources. Calling the Dispose method ensures that those unmanaged resources will be properly released.

Deleting an object from the heap is what the Garbage Collector does and when this happens is a non-deterministic event (you have no control over it).

like image 188
Darin Dimitrov Avatar answered Oct 21 '22 16:10

Darin Dimitrov