PRB: Managed Object Is Not Garbage Collected When the Managed Object Handles an Event for an Unmanaged (COM) Object (815120)
The information in this article applies to:
- Microsoft .NET Framework 1.1
- Microsoft .NET Framework 1.0
SYMPTOMSWhen a managed object contains a reference to an unmanaged
(COM) object, and an event handler is added to the managed object to handle
the event that is raised by the unmanaged object, the managed object is not garbage
collected.WORKAROUNDTo work around the problem, follow these steps:
- Implement the IDisposable interface in the managed class.
- In the Dispose method, write code to free all the components. Set
the oVB6 object to Nothing. Suppress the Finalize method.
- Call the Dispose method of the managed object before you set the managed object to
Nothing.
- Follow steps 1 through 6 in the "Create a Microsoft Visual Basic .NET Console Application to Reproduce the Behavior" section. Replace the code in step 7 with the following code:
Module Module1
Sub Main()
Dim c1 As Class1 = New Class1
Dim wr As System.WeakReference = New WeakReference(c1)
c1.Dispose()
c1 = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
Console.WriteLine("Is object alive: " & wr.IsAlive)
Console.ReadLine()
End Sub
End Module
Public Class Class1
Implements IDisposable
Private oVB6 As Project1.Class1Class
Public Sub New()
oVB6 = New Project1.Class1Class
AddHandler oVB6.MyEvent, AddressOf Me.OnMyEvent
End Sub
Sub OnMyEvent()
'
End Sub
Public Sub Dispose() Implements System.IDisposable.Dispose
oVB6 = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
GC.SuppressFinalize(Me)
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
End Class - Run the application with the workaround. You may
notice that the object is now garbage collected successfully. When you run the
code sample that is mentioned in the "More Information" section, you receive the following error message in the Console window:
"Is
object alive: False"
STATUS This
behavior is by design.REFERENCESFor more information about automatic memory management, visit
the following Microsoft Developer Network (MSDN) Web site:
Modification Type: | Minor | Last Reviewed: | 7/18/2003 |
---|
Keywords: | kbDLL kbConsole kbGarbageCollect dtssb kbCOMInterop kbprb KB815120 kbAudDeveloper |
---|
|