Are there any downsides to using Using
? I understand that outside of a Using
block I'm not going to be able to use that resource but are there circumstances where I should leave it to the garbage collector?
Here is some example code with nested using
s.
Dim ftpReq As FtpWebRequest = Nothing
subSetupFtp(ftpReq, WebRequestMethods.Ftp.ListDirectory) 'Setup FTP
Dim lstFileNames As New List(Of String)
'Get FTP response
Using webRes As WebResponse = ftpReq.GetResponse()
'read filenames into list to return
Using ftpStream As New StreamReader(webRes.GetResponseStream())
Do While ftpStream.Peek <> -1
lstFileNames.Add(ftpStream.ReadLine)
Loop
lstFileNames.Sort() 'alphabetically sorts the list(a-z) ie. The files are now in date order
'Tidy up
ftpStream.Close()
webRes.Close()
End Using
End Using
If an object has IDisposable implemented with then, it is always better to use it with Using
, which internally works as a try / finally block. This will ensure its disposal even if any exception occurs.
circumstances where i should leave it to the garbage collector?
The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.