I am trying to figure out the best way to use a DataSet
/DataTable
and cleaning up properly afterwards.
I am a little puzzled as to what causes memory to be released. I tested my theory with a test application where I populated the same DataTable
multiple times in a loop and looking at Windows' Task Manager for the memory footprint after 3 forced GC collects.
What I found is that:
If I did not call
Clear
orDispose
, or set theDataTable
variable toNothing
, the final memory consumption in Task Manager was about 30k.If I just set the variable to
Nothing
inside the loop, the final memory was about 15k.
Question: Why does setting the variable toNothing
make a difference?If I called only the
Dispose
method inside the loop, the final memory was about 19k.If I called only
Clear
inside the loop, the final memory was about 16.5k. In fact, it did not change even after theGC.Collect
.
I would really appreciate if someone can share what is the best way to use and cleanup DataSet
s when no longer needed.
Sample code is shown below.
Imports System.Data.SqlClient;
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Test()
GC.Collect()
GC.Collect()
GC.Collect() 'Throw in one more
End Sub
Private Sub Test()
Dim oDA As SqlDataAdapter = Nothing
Dim oConn As SqlConnection = Nothing
Dim oCommand As SqlCommand = Nothing
Dim ods As DataSet = Nothing
Dim oDt As DataTable = Nothing
Try
oConn = New SqlConnection("Server=Myserv;Database=myDB;UserId=myuserid;Password=mypassword;")
oCommand = New SqlCommand("Select * from Users", oConn)
oConn.Open()
ods = New DataSet
oDA = New SqlDataAdapter(oCommand)
For i As Integer = 0 To 50
oDA.Fill(ods)
oDt = ods.Tables(0)
'oDt.Clear()
'oDt.Dispose()
oDt = Nothing
Next
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
ods.Clear()
ods = Nothing
oConn.Close()
oDA = Nothing
End Try
End Sub
End Class
Edit: I am looking for best practices for managing memory of DataSet
s and/or DataTable
s that are passed around, where the creating method is not necessarily tasked with cleaning up the memory. Also, why does setting an object/variable to Nothing
within a function performs differently than just letting it go out of scope.