How to use Dispose?

I am just wondering how to code Dispose. OK, I check for each control anddatabase objects used in the code for not being nulls and if so, I disposethem individually and setting them to null. Not sure if this is correct. ButI am not clear from where to call this method from.

Share:

3 Answers Found

You can call Dispose() method when you stop using certain instance of an object.But Garbage collector will dispose resources as needed, so Dispose itselfdoesn't actually free memory and other resources...

Ok, I understand that but on a web page, when it is guided by userevents/activities, how do I know that when the user would close the browserbefore which I could dispose objects like datagrid. I may dispose Connectionobjects etc. but I can not call dispose for all the objects .

You have to know how ASP.NET works. On everypostback the application recreatescomplete Page's control tree. If any event handler creates something more, eventhat is created. After the Response is sent to the user, all resources arereleased (as disposed to Garbage Collector -GC). If between your postbacksomeone else (another user session) needs more memory, garbage collector willfisically free your resources and by your postback they would have to berecreated a new. Otherwise they'll be pulled of the memory.

What I wanted to say is that every visit to the page regreates all the controlsto the memory (totaly fresh or not disposed from the GC). So You don't have toworry so much about users that close their windows, because their resources arealready in the hands of GC. They will be relesed from the memory as soon as theserver will need more memory resources.

It's different with database connections which are a "time consuming" objects.It's normal to close a connection because it communicates with another app (oreven computer), but the connection object is also disposed to GC and released byGC when needed.

The only thing to remember is that ASP.NET application creates all the objectson every request to any page included in the application.When there are no request, there are also no object instances. But memory can be"occupied" but is marked as "freeable" by the GC.