Bug 41202 - "System.ArgumentException: GCHandle value belongs to a different domain" is thrown when I hold strong reference with GCHandle and delete it in finalizer
Summary: "System.ArgumentException: GCHandle value belongs to a different domain" is t...
Status: ASSIGNED
Alias: None
Product: Runtime
Classification: Mono
Component: GC (show other bugs)
Version: 4.2.0 (C6)
Hardware: PC Windows
: --- normal
Target Milestone: ---
Assignee: Vlad Brezae
URL:
Depends on:
Blocks:
 
Reported: 2016-05-20 08:03 UTC by xvroad@gmail.com
Modified: 2016-07-21 05:39 UTC (History)
3 users (show)

See Also:
Tags:
Is this bug a regression?: ---
Last known good build:


Attachments

Description xvroad@gmail.com 2016-05-20 08:03:13 UTC
This code runs fine on Microsoft's runtime, but not on Mono for Windows v4.2.3. My application exits with exception when I close it. Is this because I'm allocating GCHandle inside finalizer?
I sometimes don't get this error for some reason.

https://github.com/vroad/lime/blob/9abbf72698cbf60ec5cbf0c648a629f5259bb525/templates/cs/src/cs/ndll/CSAbstract.cs#L49

Unhandled Exception:
System.ArgumentException: GCHandle value belongs to a different domain
  at System.Runtime.InteropServices.GCHandle.op_Explicit (IntPtr value) <0x36c84
08 + 0x00093> in <filename unknown>:0
  at System.Runtime.InteropServices.GCHandle.FromIntPtr (IntPtr value) <0x36c83d
0 + 0x00017> in <filename unknown>:0
  at cs.ndll.HandleUtils.GetObjectFromIntPtr (IntPtr ptr) <0x36c8370 + 0x00033>
in <filename unknown>:0
  at cs.ndll.CFFICSLoader.cs_destroy_root (IntPtr inValue) <0x3712280 + 0x00013>
 in <filename unknown>:0
  at (wrapper native-to-managed) cs.ndll.CFFICSLoader:cs_destroy_root (intptr)
  at (wrapper managed-to-native) System.Object:wrapper_native_03C92590 (intptr)
  at cs.ndll.CSAbstract.Dispose (Boolean disposing) <0x8ccb230 + 0x00068> in <fi
lename unknown>:0
  at cs.ndll.CSAbstract.Finalize () <0x8ccb1e8 + 0x0001b> in <filename unknown>:
0
Comment 1 xvroad@gmail.com 2016-05-20 09:41:42 UTC
It turned out to be another issue. This only occurs when I hold strong reference from C++ with GCHandle, and release it in C# finalizer by calling C++ cleanup function.
Comment 2 xvroad@gmail.com 2016-05-20 13:28:43 UTC
I avoided this problem by moving GCHandle to outside of CSPersistent class. I don't know why Microsoft's runtime didn't throw exceptions or crash, maybe it's handling this issue in a different way. Does this suggest that another bug exists in Mono, or is it completely my fault?

I've also tried older code on v4.4.0. Mono crashed without showing error messages.

So I learned that I shouldn't hold reference to this object and free it in Dispose method.
This will cause circular reference issues, at least on Mono.
Comment 3 Rodrigo Kumpera 2016-07-21 05:39:54 UTC
Vlad,

Can you take a look at this issue?

Note You need to log in before you can comment on or make changes to this bug.