I am using Implements Idisposable
inside a Class object because of a callback exception being thrown during calls to a DLL inside a method in the Class. The thinking is that the Class was undergoing garbage collection too early when the DLL was still processing.
However, I found and used some code from MSDN (below) and replaced the auto-created code at the end of the class with this code and it seems to work:
#Region "IDisposable"
'---Code entirely copied from MSDN
Private managedResource As System.ComponentModel.Component
Private unmanagedResource As IntPtr
Protected disposed As Boolean = False
Protected Overridable Overloads Sub Dispose(
ByVal disposing As Boolean)
If Not Me.disposed Then
If disposing Then
Try
managedResource.Dispose()
Catch
End Try
End If
' Add code here to release the unmanaged resource.
unmanagedResource = IntPtr.Zero
' Note that this is not thread safe.
End If
Me.disposed = True
End Sub
'Private Sub AnyOtherMethods()
'If Me.disposed Then
'Throw New ObjectDisposedException(Me.GetType().ToString, "This object has been disposed.")
'End If
'End Sub
'Do not change or add Overridable to these methods.
'Put cleanup code in Dispose(ByVal disposing As Boolean).
Public Overloads Sub Dispose() Implements IDisposable.Dispose
' Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overrides Sub Finalize()
' Dispose(False)
MyBase.Finalize()
End Sub
#End Region
There is one caveat: if after instantiating the class, I loop and wait for a global Boolean parameter to be set to true at the end of the method inside the class (which calls the DLL), then dispose the object, the callback error will appear.
Public ProcFinished As Boolean
Public Class ProcClass
Sub New(param1, param2, param3)
MyMethodThatCallsDLL(param1, param2, param3)
End Sub
Sub MyMethodThatCallsDLL(param1, param2, param3)
'Call DLL
ReferenceName.DLLName(param1, param2, param3)
'...do some math...
ProcFinished = True
End Sub
End Class
'...somewhere else in Project
ProcFinished = False
Dim myproc As New ProcClass(param1, param2, param3)
Do Until ProcFinished = True 'waits till Public ProcFinished is True
Loop
myproc.Dispose() '(don't know if this is needed?)
The question is whether the myproc.Dispose() code above is required, given the IDiposable code? I cannot intepret the IDisposable code that well, but it does look like there is some trickery for assigning the class as managed code, so it doesn't get killed by GC(?)