Public Sub DisposedEventExample()
' Create an image
Dim image1 As RasterImage = New RasterImage(RasterMemoryFlags.Conventional, 100, 100, 24, RasterByteOrder.Bgr, RasterViewPerspective.TopLeft, Nothing, Nothing, 0)
' Add a handler to the Disposed event
Debug.WriteLine("Adding handler to Disposed for image with format " & image1.OriginalFormat)
AddHandler image1.Disposed, AddressOf rasterImage_Disposed
' Now dispose the image
Debug.WriteLine("Calling .Dispose to image with format " & image1.OriginalFormat)
image1.Dispose()
' Now use the "using" syntax
Using image2 As RasterImage = New RasterImage(RasterMemoryFlags.Conventional, 100, 100, 24, RasterByteOrder.Bgr, RasterViewPerspective.TopLeft, Nothing, Nothing, 0)
' Add a handler to the Disposed event
Debug.WriteLine("Adding handler to Disposed for image with format " & image2.OriginalFormat)
AddHandler image2.Disposed, AddressOf rasterImage_Disposed
' The event should occur at the next line
Debug.WriteLine("Will be disposed after this, format " & image2.OriginalFormat)
End Using
' Load another image
Dim image3 As RasterImage = New RasterImage(RasterMemoryFlags.Conventional, 100, 100, 24, RasterByteOrder.Bgr, RasterViewPerspective.TopLeft, Nothing, Nothing, 0)
' Add a handler to the Disposed event
Debug.WriteLine("Adding handler to Disposed for image with format " & image3.OriginalFormat)
AddHandler image3.Disposed, AddressOf rasterImage_Disposed
' Do not dispose the image
Debug.WriteLine("Never disposing image with format " & image3.OriginalFormat)
' Notice that the event will never occur for image3. The image is not going to be disposed
' only its finalizer called. The garbage collector cannot guarantee that our event handler
' is still a valid object. This scenario creates resource leaks and it is recommended that
' you always dispose and object that implements the IDisposable interface, like we did
' with image1 and image2
End Sub
Private Sub rasterImage_Disposed(ByVal sender As Object, ByVal e As EventArgs)
' Get the RasterImage object being disposed
Dim image As RasterImage = TryCast(sender, RasterImage)
Debug.WriteLine("Being disposed, image with format " & image.OriginalFormat)
' Remove the handler to decouple the object from our application
' and let the garbage collector take over
RemoveHandler image.Disposed, AddressOf rasterImage_Disposed
End Sub |