However, see the next Note in the text!
Let??™s revisit the Win32Heap example from the previous section and modify it with a finalizer.
Follow the recommended Disposable pattern, and see how it changes:
Imports System
Imports System.Runtime.InteropServices
Public Class Win32Heap
Implements IDisposable
Private theHeap As IntPtr
Private disposed As Boolean = False
_
Shared Function HeapCreate(ByVal flOptions As UInteger, _
ByVal dwInitialSize As UIntPtr, ByVal dwMaximumSize As UIntPtr) As IntPtr
End Function
_
Shared Function HeapDestroy(ByVal hHeap As IntPtr) As Boolean
End Function
Public Sub New()
theHeap = HeapCreate(0, CType(4096, UIntPtr), UIntPtr.Zero)
End Sub
CHAPTER 14 n VB 2008 BEST PRACTICES 338
'IDisposable implementation
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If (Not disposed) Then
If disposing Then
'It's OK to use any internal objects here.
'This class happens not to have any.
End If
'If using objects that you know do still exist, such as objects
'that implement the singleton pattern, it is important to make
'sure those objects are thread-safe.
HeapDestroy(theHeap)
theHeap = IntPtr.Zero
disposed = True
End If
End Sub
Public Sub Dispose() Implements IDisposable.
Pages:
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551