I have some sample webservice like below,
<WebMethod()> _
Public Function ExecuteCMD() As Boolean
Dim cnn As New Data.SqlClient.SqlConnection
Try
cnn.ConnectionString = "ConnectionString Here"
cnn.Open()
Dim cmd As New Data.SqlClient.SqlCommand("CommandText Here", cn)
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Return False
End Try
End Function
Normally,we always close the connection after using it,
but there has never call close method.
Some of my friends said that
webservice is stateless method and it doesn’t matter
whether we have
close it or not.Is it true?I also know that cnn object life time is in
only that method and visualstudio will dispose it end of that method.
I really want to know object lifetime,how they allocated on memory and
when they are disposed after using.
Best Regards,
Chong
It does matter if you close the connection or not. SQL Server is quite resilient against lingering unclosed connections, but if you for example used Access you would quickly run out of available connections and get an error message when you tried to connect.
You have a connection object and a command object which both are disposable, so you should dispose them. Letting them go out of scope is not enough, the .NET memory management doesn’t work that way. The IDisposable interface is intended for objects with unmanaged resources that need to be cleared up.
Most disposable objects has a finaliser as fallback if you fail to dispose them, so they will be cleaned up eventually, but you want to aviod that. You want to dispose the objects as soon as possible, otherwise they will remain in memory until the garbage collector comes around to clean them up.
A
Usingblock around the code where a disposable object is used is a good way to make sure that it’s disposed properly. It uses aTry...Finallyblock to ensure that the object is always disposed even if an error occurs.