Bug 24974

Summary: Exception occurs in __ComObject finalizer when shutting down process
Product: [Mono] Class Libraries Reporter: daspits
Component: mscorlibAssignee: Bugzilla <bugzilla>
Status: RESOLVED FIXED    
Severity: normal CC: bernhard.urban, eb1, mono-bugs+mono
Priority: ---    
Version: 3.4.0   
Target Milestone: Untriaged   
Hardware: PC   
OS: Linux   
Tags: Is this bug a regression?: ---
Last known good build:

Description daspits 2014-12-02 01:32:40 UTC
An exception can occur when finalizing a __ComObject. It specifically occurs when shutting down the process. The __ComObject finalizer attempts to call ReleaseInterfaces on the thread it was created on using a synchronization context. If the synchronization context is a WinForms synchronization context, it uses a socket to make asynchronous calls. If the socket is finalized prior to the __ComObject, then an ObjectDisposedException or SocketException is thrown when the __ComObject tries to use the synchronization context.

All RCWs/__ComObjects are cleaned up prior to the last finalization is performed on the finalizer thread. The list of RCWs is maintained by caching all ComInteropProxy objects that are currently active. Each __ComObject should have a corresponding ComInteropProxy, which holds a reference to the __ComObject. This reference is used to clean up the __ComObject during runtime shutdown. It seems as though the garbage collector will often collect ComInteropProxy objects that still have RCWs that are in use. I believe this happens because the __ComObject does not reference the ComInteropProxy. Any __ComObjects that have no ComInteropProxy are not cleaned up during shutdown, leaving them to be finalized during the last finalization, which can happen after the synchronization context it references has been finalized.

I believe that this problem can be fixed by having the __ComObject reference its ComInteropProxy and by having the __ComObject check in the finalizer if it has already been cleaned up by checking if the itf_hash field is null.
Comment 1 eb1 2016-01-29 21:53:12 UTC
Suggested fix in https://github.com/mono/mono/pull/2545