Re: Beginner's question re: DataSets and the dispose method [C#] by Robert
Robert
Sat Oct 23 02:12:22 CDT 2004
All variables are managed by the CLR GC (Common Language Runtime Garbage
Collector).
This means that 95% of the time, you don't have to worry about manging your
memory in a .NET application. THe exception to the rule is a disposable
object. When you are through with an object (say if you reassign it), the
CLR will mark the object for garbage collection, but it may not (and
probably won't) delete it right away. This means that that the memory may
remain unavailable to the rest of the system until the CLR decides it's time
to "take out the garbage", in which case it will call Dispose on all objects
that implement IDisposable before it frees them.
David is right: 99% of the time, you want to call Dispose as soon as you're
done with the object. In the case of a control (Say a windows form): if you
create the dataset on construction, dispose of it when the control's dispose
is called. If you do not call dispose, then it won't be the end of the
world; the object will get disposed of when GC is run, however it will
probably cause the GC to run more often which will adversely affect
performance. For a dataset, not disposing manually will probably just cause
a small performance hit. For something like a database connection, however,
you're looking at something much more serious.
To answer your question in short: Unless you want a possible memory leak,
always dispose of objects as soon as it's safe. ALways set the object
reference to Null (Nothing in VB) after calling dispose, to ensure it's not
used again.
Also, try and put the call to dispose in a finally block to ensure the
memory is always cleaned up. Because the dispose often cleans up unmanaged
resources, if an exception causes the dispose to be overlooked, you may end
up with a nasty memory leak.
--ROBERT
"Jim Bancroft" <bobgambles@nowhere.com> wrote in message
news:u$ZG3fHuEHA.1308@tk2msftngp13.phx.gbl...
> Hi everyone,
>
> I suppose this question reaches a little further than just DataSets,
but
> I was wondering if I should/need to call the Dispose() method on a DataSet
> I'm about to reassign. For instance:
>
> DataSet m_DataSet = new DataSet("My DataSet");
> //do something below here...
>
> //now, in the same method, reassign m_DataSet. But should I call
Dispose()
> first?
> m_DataSet = new DataSet("Another DataSet");
>
> I'm not sure if just reassigning the m_DataSet variable (without calling
> Dispose) is ok or maybe not the best practice. Or, is it a Bad Idea,
> capitalized and underscored?
>
> Thanks for the help.
>
> -Jim
>
>
>
>