Groups | Blog | Home
all groups > vb.net data > february 2006 >

vb.net data : Are the Dispose and Close methods necessary?


Steve Lynch
2/28/2006 3:12:14 PM

I'm just learning about the DataAdapter, SqlConnection/OracleConnection,
OracleCommand/SqlCommand. I'm just curious if the Dispose() and Close() methods
are necessary, or if they're called automatically when the variable goes out of
scope. For example, in this code I don't think they are really necessary, will
they get called automatically?


Private Function GetOracleDataSet(ByVal ConnectionName As String, _
ByVal SQLStatement As String, _
ByRef ds As DataSet, _
ByVal TableName As String) As Integer
Dim settings As ConnectionStringSettings
settings = ConfigurationManager.ConnectionStrings(ConnectionName)
Dim ConnectString As String = settings.ConnectionString
Dim conn As New OracleConnection(ConnectString)

Dim cmd As OracleCommand = conn.CreateCommand()

cmd.CommandText = SQLStatement
cmd.CommandType = CommandType.Text

Dim da As New OracleDataAdapter(cmd)
da.Fill(ds, TableName)

da.Dispose()
cmd.Dispose()
conn.Close()
conn.Dispose()
End Function


Also, if you call Dispose does that call Close automatically?


William (Bill) Vaughn
2/28/2006 6:39:37 PM
Rule #1 in .NET. Never depend on the GC to close/dispose objects--especially
connections. The GC does not run periodically or when an object goes out of
scope as it did in VB6. It runs only when needed--as when memory has all
been allocated. This means it might not run for days. If you're done with a
Connection, close it.

--
____________________________________
William (Bill) Vaughn
Author, Mentor, Consultant
Microsoft MVP
INETA Speaker
www.betav.com/blog/billva
www.betav.com
Please reply only to the newsgroup so that others can benefit.
This posting is provided "AS IS" with no warranties, and confers no rights.
__________________________________

[quoted text, click to view]

AddThis Social Bookmark Button