Scythen <Sc*****@discussions.microsoft.comwrote:
I have some code similar to the following:
C#
MyClass mVer = ne w MyClass();
?in a member function
mVar.SendEvent( new Event() );
Managed C++
Ref class MyClass
{
Void SendEvent( Event^ event )
{
// event is collected by the GC during this call... why?
mUnmanagedPtr->SendUnmanagedEvent( event->GetUnmanagedEvent() );
}
}
For some reason the GC thinks its ok to collect the managed event object
before SendUnmanagedEvent returns. Standard scope rules dictate that event is
referenced until the C# mVar.SendEvent function returns. At least that?s my
understanding. Because of this strange behavior I get random crashes when the
GC occasionally collects my events during the call.
Is this a bug? Is my expectation wrong? Am I doing something wrong?
Your expectation is incorrect.
The garbage collector is free to collect the object as soon as the JIT
can tell that the reference itself is no longer used.
Now, in your code that means that unless event->GetUnmanagedEvent()
returns something which in turn references event itself, there's
nothing referencing the Event object any more and it can be garbage
collected.
From the Unified C# 3.0 spec:
<quote>
2. If the object, or any part of it, cannot be accessed by any
possible continuation of execution, other than the running of
destructors, the object is considered no longer in use, and it becomes
eligible for destruction. The C# compiler and the garbage collector may
choose to analyze code to determine which references to an object may
be used in the future. For instance, if a local variable that is in
scope is the only existing reference to an object, but that local
variable is never referred to in any possible continuation of execution
from the current execution point in the procedure, the garbage
collector may (but is not required to) treat the object as no longer in
use.
</quote>
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too