I have never posted on this forum before but use it a lot for research, but this time I could not find an answer… maybe I am just not wording it correctly.
I am using the SqlCeCommand quite a lot in a Compact Framework project I have been working on for a while and have had a number of issues with running out of memory, so I’m trying to optimize the unmanaged code parts better.
Take a look at this:
Dim SQLCmd as SQLCeCommand
SQLCmd = New SQLCeCommand
SQLCmd.Connection = conndb
... Process db stuff
SQLCmd = New SQLCeCommand
SQLCmd.Connection = conndb
... Process db stuff
SQLCmd = New SQLCeCommand
SQLCmd.Connection = conndb
... Process db stuff
SQLCmd.Dispose()
Is this OK, or do I lose the memory each time I call New on the same object ? The reason why I was doing this rather than keeping the same instance of the object was so I did not have to explicitly set the SQLCmd properties each time. As some might use parameters and some might not so I thought using new would be an easier way of making sure everything was clear.
Any thoughts or a better way to approach this ?
In your code, everytime you call New the previous reference is lost and then it is the garbage collector work that frees, the now, unreferenced object. This happens when the Garbage Collector framework decides that it is time to get back the memory and thus it doesn’t happen immediately
To do a better work you could use the Using statement
In this way you call Dispose automatically for the previouse SqlCmd and give to the Garbage Collector a strong hint to collect the unused memory.
From MSDN