Visual Basic .NETIDisposable的基本概念
示例
任何时候实例化一个Implements的类,当您使用完该类时IDisposable,都应该在该类上调用.Dispose1。这允许类清除它可能正在使用的任何托管或非托管依赖项。不这样做可能导致内存泄漏。
该Using关键字可确保.Dispose被调用时,您无需显式调用它。
例如没有Using:
Dim sr As New StreamReader("C:\foo.txt")
Dim line = sr.ReadLine
sr.Dispose()现在Using:
Using sr As New StreamReader("C:\foo.txt")
Dim line = sr.ReadLine
End Using '.Dispose is called here for you一个主要的优点Using是当引发异常时,因为它确保.Dispose被调用。
考虑以下。如果抛出异常,则需要记住要调用.Dispose,但是您可能还必须检查对象的状态,以确保不会出现空引用错误等。
Dim sr As StreamReader = Nothing
Try
sr = New StreamReader("C:\foo.txt")
Dim line = sr.ReadLine
Catch ex As Exception
'Handle the Exception
Finally
If sr IsNot Nothing Then sr.Dispose()
End Tryusing块意味着您不必记住要执行此操作,并且可以在内声明对象try:
Try
Using sr As New StreamReader("C:\foo.txt")
Dim line = sr.ReadLine
End Using
Catch ex As Exception
'sr is disposed at this point
End Try1我是否总是需要调用Dispose()DbContext对象?不