[Mono-dev] Why does .NET object lifetime not extend into an instance method call?
davidj at gmail.com
Fri Aug 24 17:11:21 UTC 2012
I know this question isn't a Mono-question per-se. However, it's a .NET
implementation topic, and I can't think of a better place to get a well
In this 2005 article on the reason for the .NET v2.0 SafeHandle construct a
GC finalizer race conditions is discussed.
If I understand it correctly, it explains that a call to an instance method
does not hold a GC reference to a "this" pointer for the duration of the
call. Thus it is possible for an object instance to be GC finalized in one
thread, while another thread still has code running inside the instance
method -- if that instance method has no more references to it's "this"
This presents a particular problem for methods with calls to PInvoke entry
points, as the thread may be inside unmanaged code using a resource when
the Finalizer closes that unmanaged resource.
My questions are:
(1) Why would a call to an instance method not hold "this" alive for the
entire duration of the call?
It seems this could happen in more cases than just PInvoke. This seems to
allow a finalizer to run before an object is "done being used" anytime the
object instance is not stored. (i.e. inside a statement of the form "new
Foo().Method();") If the finalizer triggers an IDispose pattern, this could
cause a managed resource to be torn down before it's done being used as
Why isn't this considered a bug in the .NET runtime?
(2) Does the Mono GC have the same behavior?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Mono-devel-list