如何解决此IDisposable代码是否需要Class Object的手册.Dipose?
我在Class对象内使用Implements Idisposable
,因为在对Class方法中的DLL进行调用期间抛出了回调异常。这种想法是,当DLL仍在处理时,Class进行垃圾回收的时间过早。
但是,我发现并使用了MSDN(如下)中的一些代码,并在该类末尾用该代码替换了自动创建的代码,它似乎可以工作:
#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
有一个警告:如果在实例化该类之后,我循环并等待在该类内部方法的最后(调用DLL)将全局布尔参数设置为true,然后处置该对象,回调错误将会出现。
Public ProcFinished As Boolean
Public Class Procclass
Sub New(param1,param2,param3)
MyMethodThatCallsDLL(param1,param3)
End Sub
Sub MyMethodThatCallsDLL(param1,param3)
'Call DLL
ReferenceName.DLLName(param1,param3)
'...do some math...
ProcFinished = True
End Sub
End Class
'...somewhere else in Project
ProcFinished = False
Dim myproc As New Procclass(param1,param3)
Do Until ProcFinished = True 'waits till Public ProcFinished is True
Loop
myproc.dispose() '(don't kNow if this is needed?)
问题是,给定IDiposable代码,是否需要上述myproc.dispose()代码?我不能很好地理解Idisposable代码,但看起来确实有些技巧,可以将类分配为托管代码,因此它不会被GC(?)杀死。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。