How to use IDisposable interface in VB.NET
IDisposable interface is to release unmanaged resources the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector.
The primary use of IDisposable interface is to release unmanaged resources. This framework would detect that an object is no longer needed as soon as it occurs and automatically free up the memory. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. This interface identifies a type that must be freed when it is no longer needed. Whenever IDisposable is implemented it is important to analyze whether a finalizer is also needed. Whenever a finalizer is defined IDisposable should also be implemented.
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.
Implementation of IDisposable
- IDisposable interface Implement Dispose method.
- Only Dispose of resources once
- A destructor is must for the class.
- Prevent the GC from disposing of resources.
IDisposable has only a single member called Dispose. This method is called when the object needs to be freed. Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.
The class's which Implement IDisposable are:
- AsymmetricAlgorithm
- BinaryReader
- BinaryWriter
- Brush
- CacheDependency
- Component
- ComponentDesigner
- Container
- Controlar
- CryptoAPITransform
- Cursor
- CustomLineCap
- DesignerTransaction
- EncoderParameter
- EncoderParameters
- EventHandlerList
- Font
- FontCollection
- FontFamily
- FromBase64Transform
- Graphics
- GraphicsPath
- GraphicsPathIterator
- HashAlgorithm
- HttpApplication
- Icon
- Image
- ImageAttributes
- IsolatedStorageFile
- Lincense
- LocalizationExtenderProvider
- ManagementObjectCollection
- ManagementObjectCollection.ManagementObjectEnumerator
- MarshalByValueComponent
- Matrix
- MessageEnumerator
- MessageQueueEnumerator
- MessageQueueTransaction
- OdbcDataReader
- OdbcTransaction
- OleDbDataReader
- OleDbTransaction
- OracleDataReader
- OracleTransaction
- PaintEventArgs
- Pen
- Region
- RegistryKey
- ResourceReader
- ResourceSet
- ResourceWriter
- ResXResourceReader
- ResXResourceWriter
- SearchResultCollection
- ServicedComponent
- Socket
- SqlCeCommand
- SqlCeConnection
- SqlCeDataReader
- SqlCeEngine
- SqlCeRemoteDataAccess
- SqlCeReplication
- SqlCeTransaction
- SqlDataReader
- SqlTransaction
- Stream
- StringFormat
- SymmetricAlgorithm
- TcpClient
- TempFileCollection
- TemplateEditingVerb
- TextReader
- TextWriter
- Timer
- ToBase64Transform
- TraceListener
- UdpClient
- WaitHandle
- WebResponse
Here's an example class implementing IDisposable:
Imports System
Imports System.Drawing
Imports System.Data
Imports System.IO
Imports System.Collections
Imports System.Windows.Forms
Imports System.Drawing.Printing
Public Class dispo
Shared Sub Main()
Dim textfile As New textfile1("c:\demo.txt")
textfile.insertvalue("Example of IDisposable")
textfile.Dispose()
textfile = Nothing
Console.WriteLine("Press Return to collect the garbage...")
GC.Collect()
Console.WriteLine("Press Return to quit...")
Console.ReadLine()
End Sub
End Class
Public Class textfile1
Implements IDisposable
Private str As FileStream
Private id As Boolean
Public Sub New(ByVal filename As String)
str = New FileStream("test.txt", FileMode.OpenOrCreate)
Console.WriteLine("Object " & GetHashCode() & " created.")
Console.WriteLine("Using file: " & filename)
End Sub
Public Sub insertvalue(ByVal buf As String)
If id = True Then
Throw New ObjectDisposedException("I've been disposed!")
End If
Dim wr As New StreamWriter(str)
wr.WriteLine(Date.Now)
wr.WriteLine(buf)
wr.Close()
End Sub
Public Sub Dispose() Implements System.IDisposable.Dispose
If id = True Then Return
str.Close()
str = Nothing
id = True
GC.SuppressFinalize(Me)
Console.WriteLine("Object " & GetHashCode() & " disposed.")
End Sub
Protected Overrides Sub Finalize()
Dispose()
Console.WriteLine("Object " & GetHashCode() & " finalized.")
End Sub
End Class
Output